// Industry Analytics — vertical dashboards: Manufacturing, Financial, HR, Retail, Healthcare, Agriculture.
function MiniKpi({ label, value, unit, delta, up, sub, color }) {
  return (
    <div className="card kpi" style={{ padding: 13 }}>
      <div className="label">{label}</div>
      <div className="value" style={{ fontSize: 23, color }}>{value}<span className="unit">{unit}</span></div>
      {delta != null
        ? <div className={`delta ${up ? 'up' : 'down'}`}><Icon name={up ? 'trending' : 'trendingDown'} size={12}/>{fmtPct(delta)} <span className="vs">{sub}</span></div>
        : <div className="delta" style={{ color: 'var(--ink-3)' }}>{sub}</div>}
    </div>
  );
}

function ChartCard({ title, sub, children, right }) {
  return (
    <div className="card">
      <div className="card-head"><div><h3>{title}</h3>{sub && <div className="sub">{sub}</div>}</div>{right || <button className="icon-btn"><Icon name="moreH"/></button>}</div>
      <div className="card-body">{children}</div>
    </div>
  );
}

const INDUSTRIES = [
  { id: "mfg", label: "Manufacturing", icon: "factory" },
  { id: "fin", label: "Financial", icon: "wallet" },
  { id: "hr", label: "Human Resources", icon: "briefcase" },
  { id: "retail", label: "Retail", icon: "cart" },
  { id: "health", label: "Healthcare", icon: "heart" },
  { id: "agri", label: "Agriculture", icon: "leaf" },
];

function IndustryScreen() {
  const [ind, setInd] = useState("mfg");
  const meta = INDUSTRIES.find(i => i.id === ind);

  return (
    <div className="screen">
      <div className="screen-head">
        <div>
          <div className="screen-title">Industry Analytics</div>
          <div className="screen-sub">Vertical intelligence packs · pre-built KPIs, models &amp; benchmarks for {meta.label}</div>
        </div>
        <div className="screen-actions">
          <button className="btn"><Icon name="calendar"/>Q2 FY26</button>
          <button className="btn"><Icon name="sparkles"/>Benchmark</button>
          <button className="btn primary"><Icon name="download"/>Export pack</button>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6, marginBottom: 16, flexWrap: 'wrap' }}>
        {INDUSTRIES.map(i => (
          <button key={i.id} onClick={() => setInd(i.id)}
            style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '7px 13px', borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: ind === i.id ? 600 : 500,
              border: '1px solid ' + (ind === i.id ? 'var(--primary)' : 'var(--border-strong)'),
              background: ind === i.id ? 'var(--primary-tint)' : 'var(--panel)', color: ind === i.id ? 'var(--primary)' : 'var(--ink-2)' }}>
            <Icon name={i.icon} size={14}/>{i.label}
          </button>
        ))}
      </div>

      {ind === "mfg" && <Manufacturing/>}
      {ind === "fin" && <Financial/>}
      {ind === "hr" && <HR/>}
      {ind === "retail" && <Retail/>}
      {ind === "health" && <Healthcare/>}
      {ind === "agri" && <Agriculture/>}
    </div>
  );
}

function Manufacturing() {
  return (
    <div className="fade-in">
      <div className="grid g-4" style={{ marginBottom: 14 }}>
        <MiniKpi label="OEE" value="82.4" unit="%" delta={2.8} up sub="vs plan 85%"/>
        <MiniKpi label="Availability" value="91.2" unit="%" delta={1.4} up sub="uptime"/>
        <MiniKpi label="Performance" value="94.1" unit="%" delta={-0.6} sub="of rated speed"/>
        <MiniKpi label="Quality (FPY)" value="96.0" unit="%" delta={0.9} up sub="first-pass yield"/>
      </div>
      <div className="grid" style={{ gridTemplateColumns: '1fr 1.4fr 1fr', marginBottom: 14 }}>
        <ChartCard title="OEE Score" sub="World-class ≥ 85%">
          <div style={{ display: 'grid', placeItems: 'center', padding: '8px 0' }}><Gauge value={82} max={100} w={200} color="var(--primary)"/></div>
        </ChartCard>
        <ChartCard title="Production vs Plan" sub="Units/day · this month">
          <LineChart series={[{ name: "Actual", data: [1180,1240,1210,1290,1260,1320,1380] }, { name: "Plan", data: [1250,1250,1300,1300,1350,1350,1400] }]} labels={["W1","W2","W3","W4","W5","W6","W7"]} h={200} colors={["var(--primary)", "var(--accent)"]}/>
        </ChartCard>
        <ChartCard title="Downtime Pareto" sub="Hours lost · 30d">
          <BarChart data={[42, 31, 24, 18, 12]} labels={["Changeover","Breakdown","Material","No operator","Quality"]} horizontal w={300} h={200} format={v => `${v}h`} color="var(--danger)"/>
        </ChartCard>
      </div>
      <ChartCard title="Machine Utilization — Line A→H" sub="% utilization · last 12 hours · live from OPC-UA" right={<span className="tag ok"><span className="live-dot"/>Streaming</span>}>
        <Heatmap rows={8} cols={12} rowLabels={["Press-A","Weld-B","CNC-C","Paint-D","Assy-E","Test-F","Pack-G","QC-H"]}
          colLabels={["12h","10","08","06","04","02","00","22","20","18","16","14"]}
          data={Array.from({ length: 8 }, (_, r) => Array.from({ length: 12 }, (_, c) => Math.round(70 + ((r * 7 + c * 5) % 30) - (r === 3 && c < 3 ? 25 : 0))))} w={760} format={v => v}/>
      </ChartCard>
    </div>
  );
}

function Financial() {
  return (
    <div className="fade-in">
      <div className="grid g-4" style={{ marginBottom: 14 }}>
        <MiniKpi label="Revenue (YTD)" value="₹3,214" unit="Cr" delta={8.2} up sub="vs FY25"/>
        <MiniKpi label="Net margin" value="18.4" unit="%" delta={-1.2} sub="margin compression"/>
        <MiniKpi label="Operating cash flow" value="₹684" unit="Cr" delta={6.1} up sub="QoQ"/>
        <MiniKpi label="Budget variance" value="+4.2" unit="%" delta={4.2} up sub="under budget"/>
      </div>
      <div className="grid" style={{ gridTemplateColumns: '1.5fr 1fr', marginBottom: 14 }}>
        <ChartCard title="Cash Flow — Operating / Investing / Financing" sub="₹ Cr · monthly">
          <LineChart series={[{ name: "Operating", data: [98,104,112,108,118,124,132] }, { name: "Financing", data: [40,38,44,42,48,46,52] }]} labels={["Jan","Feb","Mar","Apr","May","Jun","Jul"]} h={210} colors={["var(--ok)", "var(--accent)"]}/>
        </ChartCard>
        <ChartCard title="Expense Breakdown" sub="Q2 FY26">
          <Donut data={[{ label: "Procurement", value: 48 }, { label: "Payroll", value: 22 }, { label: "Opex", value: 16 }, { label: "Capex", value: 9 }, { label: "Other", value: 5 }]} w={130} centerLabel="₹2.1K" centerSub="Cr"/>
        </ChartCard>
      </div>
      <ChartCard title="Budget vs Actual — by Department" sub="₹ Cr · YTD">
        <BarChart data={[428, 386, 284, 218, 168, 152]} labels={["Railways","Defence","Health","Rural Dev","Posts","Power"]} h={220} showValue format={v => `₹${v}`} color="var(--primary)"/>
      </ChartCard>
    </div>
  );
}

function HR() {
  return (
    <div className="fade-in">
      <div className="grid g-4" style={{ marginBottom: 14 }}>
        <MiniKpi label="Headcount" value="12,480" unit="" delta={2.1} up sub="vs last qtr"/>
        <MiniKpi label="Attrition (annualized)" value="9.4" unit="%" delta={-1.8} up sub="improving"/>
        <MiniKpi label="Attendance" value="94.6" unit="%" delta={0.4} up sub="present ratio"/>
        <MiniKpi label="Avg tenure" value="6.2" unit="yrs" delta={null} sub="median 5.1 yrs"/>
      </div>
      <div className="grid" style={{ gridTemplateColumns: '1.5fr 1fr', marginBottom: 14 }}>
        <ChartCard title="Attrition Trend" sub="Voluntary vs involuntary · % monthly">
          <LineChart series={[{ name: "Voluntary", data: [1.1,1.0,0.9,0.8,0.8,0.7,0.7] }, { name: "Involuntary", data: [0.4,0.3,0.4,0.3,0.3,0.2,0.2] }]} labels={["Jan","Feb","Mar","Apr","May","Jun","Jul"]} h={210} colors={["var(--danger)", "var(--accent)"]} yFormat={v => v + '%'}/>
        </ChartCard>
        <ChartCard title="Workforce Mix" sub="By employment type">
          <Donut data={[{ label: "Permanent", value: 68 }, { label: "Contract", value: 22 }, { label: "Consultant", value: 7 }, { label: "Intern", value: 3 }]} w={130} centerLabel="12.5K" centerSub="staff"/>
        </ChartCard>
      </div>
      <ChartCard title="Headcount by Department" sub="Full-time equivalents">
        <BarChart data={[3420, 2840, 1980, 1640, 1280, 920]} labels={["Operations","Engineering","Field","Finance","IT","Admin"]} h={220} showValue format={fmtNum} color="var(--primary)"/>
      </ChartCard>
    </div>
  );
}

function Retail() {
  return (
    <div className="fade-in">
      <div className="grid g-4" style={{ marginBottom: 14 }}>
        <MiniKpi label="Net sales" value="₹482" unit="Cr" delta={11.4} up sub="vs last month"/>
        <MiniKpi label="Footfall" value="2.4" unit="M" delta={6.8} up sub="store visits"/>
        <MiniKpi label="Avg basket" value="₹1,284" unit="" delta={3.2} up sub="per txn"/>
        <MiniKpi label="Conversion" value="28.6" unit="%" delta={-0.9} sub="visit→buy"/>
      </div>
      <div className="grid" style={{ gridTemplateColumns: '1.5fr 1fr', marginBottom: 14 }}>
        <ChartCard title="Sales Trend" sub="₹ Cr · daily this month">
          <LineChart series={[{ name: "Sales", data: [12,14,13,16,18,22,20,24,26,23,28,30] }]} labels={["1","3","5","7","9","11","13","15","17","19","21","23"]} h={210}/>
        </ChartCard>
        <ChartCard title="Customer Segments" sub="RFM analysis">
          <Donut data={[{ label: "Champions", value: 24 }, { label: "Loyal", value: 31 }, { label: "At risk", value: 18 }, { label: "New", value: 15 }, { label: "Dormant", value: 12 }]} w={130} centerLabel="1.8M" centerSub="customers"/>
        </ChartCard>
      </div>
      <ChartCard title="Sales by Category" sub="₹ Cr · Q2">
        <BarChart data={[142, 118, 96, 74, 52]} labels={["Apparel","Electronics","Grocery","Home","Beauty"]} horizontal w={760} h={180} format={v => `₹${v}Cr`} color="var(--primary)" accent="var(--accent)"/>
      </ChartCard>
    </div>
  );
}

function Healthcare() {
  return (
    <div className="fade-in">
      <div className="grid g-4" style={{ marginBottom: 14 }}>
        <MiniKpi label="Patients (OPD, 30d)" value="184K" unit="" delta={4.6} up sub="vs last month"/>
        <MiniKpi label="Bed occupancy" value="86.2" unit="%" delta={2.1} sub="of 4,200 beds"/>
        <MiniKpi label="Avg length of stay" value="3.8" unit="days" delta={-4.2} up sub="improving"/>
        <MiniKpi label="Patient satisfaction" value="4.4" unit="/5" delta={0.2} up sub="NPS +38"/>
      </div>
      <div className="grid" style={{ gridTemplateColumns: '1.5fr 1fr', marginBottom: 14 }}>
        <ChartCard title="Admissions vs Discharges" sub="Daily · this week">
          <LineChart series={[{ name: "Admissions", data: [420,448,432,468,490,510,486] }, { name: "Discharges", data: [400,420,438,442,470,488,492] }]} labels={["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]} h={210} colors={["var(--primary)", "var(--ok)"]}/>
        </ChartCard>
        <ChartCard title="Case Mix" sub="By specialty">
          <Donut data={[{ label: "General med", value: 32 }, { label: "Cardiology", value: 18 }, { label: "Ortho", value: 16 }, { label: "Paediatrics", value: 14 }, { label: "Other", value: 20 }]} w={130} centerLabel="86%" centerSub="occupancy"/>
        </ChartCard>
      </div>
      <ChartCard title="Department Load — Bed Occupancy %" sub="Live from HIS">
        <BarChart data={[94, 88, 82, 76, 68, 54]} labels={["ICU","Emergency","Cardiology","General","Paediatric","Maternity"]} h={220} showValue format={v => `${v}%`} color="var(--primary)"/>
      </ChartCard>
    </div>
  );
}

function Agriculture() {
  return (
    <div className="fade-in">
      <div className="grid g-4" style={{ marginBottom: 14 }}>
        <MiniKpi label="Area sown" value="4.28" unit="M ha" delta={3.4} up sub="vs last kharif"/>
        <MiniKpi label="Avg yield" value="42.6" unit="q/ha" delta={5.8} up sub="vs 5-yr avg"/>
        <MiniKpi label="Soil moisture" value="62" unit="%" delta={null} sub="optimal 55–70%"/>
        <MiniKpi label="Advisories sent" value="1.2M" unit="" delta={null} sub="SMS + voice · 12 langs"/>
      </div>
      <div className="grid" style={{ gridTemplateColumns: '1.5fr 1fr', marginBottom: 14 }}>
        <ChartCard title="Rainfall vs Yield Index" sub="Monsoon correlation · monthly">
          <LineChart series={[{ name: "Rainfall (mm)", data: [40,120,280,340,310,180,90] }, { name: "Yield index", data: [60,88,120,140,138,110,96] }]} labels={["Jun","Jul","Aug","Sep","Oct","Nov","Dec"]} h={210} colors={["var(--info)", "var(--ok)"]}/>
        </ChartCard>
        <ChartCard title="Crop Mix" sub="By area sown">
          <Donut data={[{ label: "Rice", value: 34 }, { label: "Wheat", value: 26 }, { label: "Pulses", value: 16 }, { label: "Cotton", value: 14 }, { label: "Other", value: 10 }]} w={130} centerLabel="4.3M" centerSub="hectares"/>
        </ChartCard>
      </div>
      <ChartCard title="Yield by Crop vs National Benchmark" sub="Quintals/hectare · drone + satellite estimate" right={<span className="tag ok"><Icon name="leaf" size={10}/>Satellite</span>}>
        <BarChart data={[62, 48, 38, 32, 28, 22]} labels={["Sugarcane","Rice","Wheat","Maize","Cotton","Pulses"]} h={220} showValue format={v => `${v}`} color="var(--ok)"/>
      </ChartCard>
    </div>
  );
}

window.IndustryScreen = IndustryScreen;
