// Semantic Layer & Modeling — business glossary, KPI catalog, relationships, data warehouse.
const GLOSSARY = [
  { term: "Sales Amount", def: "Net value of a confirmed order after discounts & taxes.", map: "SUM(tbl_sales.sale_amt)", owner: "Finance BI", status: "Certified" },
  { term: "GeM Procurement Value", def: "Total awarded order value on the GeM portal in a period.", map: "SUM(gem_transactions.order_value)", owner: "Procurement", status: "Certified" },
  { term: "Vendor", def: "A registered supplier/bidder with a unique GeM seller ID.", map: "vendor_master.vendor_id", owner: "Vendor Mgmt", status: "Certified" },
  { term: "L1 Bidder", def: "Lowest-priced technically-qualified bidder for a tender.", map: "MIN(tender_bids.bid_value) WHERE qualified", owner: "Procurement", status: "Certified" },
  { term: "Scheme Beneficiary", def: "An individual/entity receiving a central-scheme disbursement.", map: "scheme_disbursement.beneficiary_id", owner: "Rural Dev.", status: "Review" },
  { term: "Fiscal Quarter", def: "Indian FY quarter (Q1 = Apr–Jun).", map: "date_dim.fiscal_qtr", owner: "Data Governance", status: "Certified" },
  { term: "MSME Vendor", def: "Vendor flagged as Micro/Small/Medium per Udyam registration.", map: "vendor_master.msme_flag = true", owner: "Vendor Mgmt", status: "Draft" },
];

const KPI_CATALOG = [
  { name: "Revenue Collection", formula: "Σ receipts_amount", unit: "₹ Cr", grain: "day · state", cert: "Gold", used: 42 },
  { name: "GeM Procurement", formula: "Σ order_value", unit: "₹ Cr", grain: "day · dept", cert: "Gold", used: 68 },
  { name: "Scheme Utilization", formula: "disbursed / allocated", unit: "%", grain: "month · scheme", cert: "Gold", used: 24 },
  { name: "Vendor Concentration", formula: "Σ (share²)  (HHI)", unit: "index", grain: "category", cert: "Silver", used: 12 },
  { name: "Days Payable", formula: "avg(paid_date − invoice_date)", unit: "days", grain: "dept", cert: "Silver", used: 18 },
  { name: "Fill Rate", formula: "delivered / ordered", unit: "%", grain: "sku · month", cert: "Gold", used: 31 },
];

function Entity({ x, y, title, fields, w = 130, highlight, kind = "dim" }) {
  const head = kind === "fact" ? "var(--primary)" : kind === "highlight" ? "var(--accent-2)" : "var(--panel-3)";
  const headText = kind === "fact" ? "white" : "var(--ink)";
  const h = 22 + fields.length * 15 + 6;
  return (
    <g transform={`translate(${x} ${y})`}>
      <rect width={w} height={h} rx="6" fill="var(--panel)" stroke={highlight ? 'var(--primary)' : 'var(--border-strong)'} strokeWidth={highlight ? 2 : 1}/>
      <path d={`M0 6 a6 6 0 0 1 6 -6 h${w - 12} a6 6 0 0 1 6 6 v16 h-${w} z`} fill={head}/>
      <text x={w / 2} y="15" fontSize="10.5" fontWeight="700" fill={headText} textAnchor="middle" fontFamily="JetBrains Mono">{title}</text>
      {fields.map((f, i) => (
        <text key={i} x="8" y={38 + i * 15} fontSize="9.5" fill={f.key ? 'var(--primary)' : 'var(--ink-2)'} fontFamily="JetBrains Mono" fontWeight={f.key ? 600 : 400}>{f.key ? '⚷ ' : '  '}{f.n}</text>
      ))}
    </g>
  );
}
function Rel({ x1, y1, x2, y2 }) {
  const mx = (x1 + x2) / 2;
  return <path d={`M ${x1} ${y1} C ${mx} ${y1}, ${mx} ${y2}, ${x2} ${y2}`} stroke="var(--primary)" strokeWidth="1.4" fill="none" opacity=".6"/>;
}

const SEM_TABS = [
  { id: "glossary", label: "Business Glossary", icon: "scale" },
  { id: "kpi", label: "KPI Catalog", icon: "target" },
  { id: "rel", label: "Relationships", icon: "link" },
  { id: "warehouse", label: "Data Warehouse", icon: "layers" },
];

function SemanticScreen() {
  const [tab, setTab] = useState("glossary");
  return (
    <div className="screen">
      <div className="screen-head">
        <div>
          <div className="screen-title">Semantic Layer &amp; Modeling</div>
          <div className="screen-sub">Business-friendly names over raw tables · 142 terms · 68 governed KPIs · single source of truth for every dashboard &amp; AI query</div>
        </div>
        <div className="screen-actions">
          <button className="btn"><Icon name="sparkles"/>AI suggest metrics</button>
          <button className="btn primary"><Icon name="plus"/>New term</button>
        </div>
      </div>

      <div style={{ borderBottom: '1px solid var(--border)', marginBottom: 16, display: 'flex', gap: 4 }}>
        {SEM_TABS.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '10px 14px', border: 'none', background: 'none', color: tab === t.id ? 'var(--ink)' : 'var(--ink-3)', fontWeight: tab === t.id ? 600 : 500, fontSize: 13, cursor: 'pointer', borderBottom: '2px solid ' + (tab === t.id ? 'var(--primary)' : 'transparent'), marginBottom: -1, fontFamily: 'inherit' }}>
            <Icon name={t.icon} size={13}/>{t.label}
          </button>
        ))}
      </div>

      {tab === "glossary" && (
        <div className="card">
          <div className="card-body" style={{ padding: 0 }}>
            <table className="data">
              <thead><tr><th>Business Term</th><th>Definition</th><th>Technical Mapping</th><th>Owner</th><th>Status</th></tr></thead>
              <tbody>
                {GLOSSARY.map((g, i) => (
                  <tr key={i}>
                    <td><div style={{ display: 'flex', alignItems: 'center', gap: 8, fontWeight: 600 }}><Icon name="scale" size={13} style={{ color: 'var(--primary)' }}/>{g.term}</div></td>
                    <td style={{ color: 'var(--ink-2)', maxWidth: 280 }} className="small">{g.def}</td>
                    <td className="mono small" style={{ color: 'var(--accent-2)' }}>{g.map}</td>
                    <td className="small" style={{ color: 'var(--ink-2)' }}>{g.owner}</td>
                    <td><span className={`tag ${g.status === 'Certified' ? 'ok' : g.status === 'Review' ? 'warn' : ''}`}>{g.status}</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === "kpi" && (
        <div className="grid g-3">
          {KPI_CATALOG.map((k, i) => (
            <div key={i} className="card" style={{ padding: 14 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--primary-tint)', display: 'grid', placeItems: 'center' }}><Icon name="target" size={15} style={{ color: 'var(--primary)' }}/></div>
                  <div><div style={{ fontWeight: 600, fontSize: 13 }}>{k.name}</div><div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>grain: {k.grain}</div></div>
                </div>
                <span className="tag" style={{ background: k.cert === 'Gold' ? 'oklch(0.94 0.06 85)' : 'oklch(0.94 0.02 250)', color: k.cert === 'Gold' ? 'oklch(0.48 0.15 65)' : 'oklch(0.42 0.05 250)', fontWeight: 600, fontSize: 10 }}>{k.cert}</span>
              </div>
              <div style={{ marginTop: 12, padding: '8px 10px', background: 'var(--panel-2)', border: '1px solid var(--border)', borderRadius: 6 }}>
                <div style={{ fontSize: 9.5, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-4)', fontWeight: 600, marginBottom: 3 }}>Formula</div>
                <div className="mono" style={{ fontSize: 12, color: 'var(--ink)' }}>{k.formula}</div>
              </div>
              <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11.5, color: 'var(--ink-3)' }}>
                <span>Unit · <b className="mono" style={{ color: 'var(--ink-2)' }}>{k.unit}</b></span>
                <span>Used in <b style={{ color: 'var(--primary)' }}>{k.used}</b> dashboards</span>
              </div>
            </div>
          ))}
        </div>
      )}

      {tab === "rel" && (
        <div className="card">
          <div className="card-head"><div><h3>Entity Relationship Model</h3><div className="sub">Auto-discovered via knowledge graph · ⚷ = key · click to inspect joins</div></div><span className="tag primary"><Icon name="sparkles" size={10}/>AI-inferred</span></div>
          <div className="card-body">
            <svg viewBox="0 0 780 300" width="100%" style={{ minWidth: 700 }}>
              <Rel x1={220} y1={120} x2={300} y2={70}/>
              <Rel x1={220} y1={140} x2={300} y2={170}/>
              <Rel x1={430} y1={150} x2={510} y2={90}/>
              <Rel x1={430} y1={170} x2={510} y2={210}/>
              <Entity x={90} y={95} title="dim_vendor" kind="dim" fields={[{ n: "vendor_id", key: true }, { n: "name" }, { n: "msme_flag" }, { n: "gst_no" }]}/>
              <Entity x={300} y={40} title="dim_department" kind="dim" fields={[{ n: "dept_id", key: true }, { n: "ministry" }]}/>
              <Entity x={300} y={130} title="fact_transaction" kind="fact" fields={[{ n: "txn_id", key: true }, { n: "vendor_id", key: true }, { n: "dept_id", key: true }, { n: "order_value" }, { n: "date_id", key: true }]}/>
              <Entity x={510} y={45} title="dim_category" kind="dim" fields={[{ n: "cat_id", key: true }, { n: "segment" }]}/>
              <Entity x={510} y={175} title="dim_date" kind="dim" fields={[{ n: "date_id", key: true }, { n: "fiscal_qtr" }, { n: "month" }]}/>
            </svg>
          </div>
        </div>
      )}

      {tab === "warehouse" && (
        <div className="grid" style={{ gridTemplateColumns: '1.6fr 1fr' }}>
          <div className="card">
            <div className="card-head"><div><h3>Star Schema — Procurement Mart</h3><div className="sub">Kimball star · 1 fact · 5 conformed dimensions</div></div></div>
            <div className="card-body">
              <svg viewBox="0 0 520 340" width="100%">
                <Rel x1={175} y1={70} x2={230} y2={150}/>
                <Rel x1={175} y1={280} x2={230} y2={185}/>
                <Rel x1={360} y1={70} x2={300} y2={150}/>
                <Rel x1={360} y1={280} x2={300} y2={185}/>
                <Rel x1={265} y1={70} x2={265} y2={140}/>
                <Entity x={210} y={140} title="fact_procurement" kind="fact" w={110} fields={[{ n: "order_value" }, { n: "qty" }, { n: "bids" }, { n: "vendor_id", key: true }, { n: "date_id", key: true }]}/>
                <Entity x={110} y={20} title="dim_vendor" fields={[{ n: "vendor_id", key: true }, { n: "name" }]}/>
                <Entity x={330} y={20} title="dim_date" fields={[{ n: "date_id", key: true }, { n: "fiscal_qtr" }]}/>
                <Entity x={110} y={250} title="dim_geo" fields={[{ n: "geo_id", key: true }, { n: "state" }]}/>
                <Entity x={330} y={250} title="dim_category" fields={[{ n: "cat_id", key: true }, { n: "segment" }]}/>
              </svg>
            </div>
          </div>
          <div className="vstack">
            {[
              { icon: "layers", t: "Storage model", v: "Lakehouse · Apache Iceberg", s: "Delta + Parquet on MinIO" },
              { icon: "database", t: "Query engine", v: "Trino + ClickHouse", s: "MPP · columnar · 12.4B rows" },
              { icon: "refresh", t: "Refresh", v: "Micro-batch · 5 min", s: "Incremental via CDC" },
              { icon: "shield", t: "Modeling standard", v: "Star + Data Vault 2.0", s: "SCD Type-2 on dimensions" },
            ].map((c, i) => (
              <div key={i} className="card" style={{ padding: 14, display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                <div style={{ width: 34, height: 34, borderRadius: 8, background: 'var(--primary-tint)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name={c.icon} size={16} style={{ color: 'var(--primary)' }}/></div>
                <div><div style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-4)', fontWeight: 600 }}>{c.t}</div><div style={{ fontSize: 13.5, fontWeight: 600, marginTop: 2 }}>{c.v}</div><div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 1 }}>{c.s}</div></div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

window.SemanticScreen = SemanticScreen;
