/* Hero — live operational dashboard tile + 2 headline variants
   Tweakable via TweaksPanel. */

const HEADLINE_VARIANTS = {
  shopfloor: {
    title: ['From Shopfloor Chaos', 'to Operational Control.'],
    sub: 'End-to-end MES/MOM implementation for complex manufacturers — ISA-95 architecture, OT/IT integration, ERP integration, shop floor digitalization, and adoption around TrakSYS.'
  },
  backbone: {
    title: ['We build the operational data backbone', 'that makes AI in manufacturing actually work.'],
    sub: 'MES implementation strategy, ISA-95 architecture, ERP integration, multi-site rollout, and shop floor digitalization — specialized in TrakSYS and vendor-agnostic on everything around it.'
  }
};

function HeroEyebrow() {
  return (
    <div className="kt-eyebrow" style={{ marginBottom: 24 }}>
      <span className="kt-eyebrow-dot"></span>
      INDUSTRIAL OPERATIONS · PORTUGAL
    </div>);

}

function HeroCTA() {
  return (
    <div style={{ display: 'flex', gap: 14, marginTop: 36, flexWrap: 'wrap' }}>
      <a href="contact.html" className="kt-btn kt-btn-primary">
        Book an Operational Diagnostic
      </a>
      <a href="case-studies.html" className="kt-btn kt-btn-ghost">
        Explore Case Studies
      </a>
    </div>);

}

/* ── Variant A: Live dashboard tile (default) ─────────────── */
function LiveDashboardTile() {
  const [oee, setOee] = React.useState(72.4);
  const [throughput, setThroughput] = React.useState(1284);
  const [downtime, setDowntime] = React.useState(48);
  const [lossPct, setLossPct] = React.useState(8.6);
  const [tick, setTick] = React.useState(0);

  React.useEffect(() => {
    const id = setInterval(() => {
      setOee((prev) => Math.max(68, Math.min(82, prev + (Math.random() - 0.45) * 0.8)));
      setThroughput((prev) => prev + Math.floor(Math.random() * 4));
      setDowntime((prev) => Math.max(20, Math.min(70, prev + (Math.random() - 0.5) * 2)));
      setLossPct((prev) => Math.max(5, Math.min(12, prev + (Math.random() - 0.5) * 0.3)));
      setTick((t) => t + 1);
    }, 1400);
    return () => clearInterval(id);
  }, []);

  // Sparkline data (rolling)
  const sparkRef = React.useRef([72, 73, 71, 74, 72, 75, 73, 76, 74, 77, 73, 75, 78, 74, 76]);
  React.useEffect(() => {
    sparkRef.current = [...sparkRef.current.slice(1), oee];
  }, [oee]);

  return (
    <div className="kt-hero-tile">
      <div className="kt-hero-tile-chrome">
        <div className="kt-hero-tile-chrome-left">
          <span className="kt-hero-tile-dot"></span>
          <span className="kt-mono" style={{ fontSize: 11, letterSpacing: '0.1em', color: 'var(--kt-navy-200)' }}>
            LIVE · LINE 03 · AMORIM SITE 12
          </span>
        </div>
        <span className="kt-mono" style={{ fontSize: 11, color: 'var(--kt-navy-400)' }}>
          {new Date().toISOString().slice(11, 19)}
        </span>
      </div>

      <div className="kt-hero-tile-grid">
        <KPI label="OEE" value={oee.toFixed(1)} unit="%" delta="+1.4" status="good" big />
        <KPI label="THROUGHPUT" value={throughput.toLocaleString()} unit="u/h" delta="+0.8%" status="good" />
        <KPI label="LOSS RATE" value={lossPct.toFixed(1)} unit="%" delta="-0.2" status="good" />
        <KPI label="UNPLANNED DT" value={downtime.toFixed(0)} unit="min" delta="+2" status="warn" />
      </div>

      <div className="kt-hero-tile-spark">
        <div className="kt-hero-tile-spark-label">
          <span className="kt-mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--kt-navy-200)' }}>
            OEE · 4H ROLLING
          </span>
          <span className="kt-mono" style={{ fontSize: 10, color: 'var(--kt-cyan-400)' }}>● TARGET 78.0</span>
        </div>
        <Sparkline data={sparkRef.current} target={78} />
      </div>

      <div className="kt-hero-tile-events">
        <EventRow time="09:42:18" code="EVT-204" text="Line 03 → batch B-2241 closed · genealogy synced to ERP" type="ok" />
        <EventRow time="09:41:02" code="EVT-198" text="Filler 02 micro-stop attributed · loss reason: nozzle-clean" type="info" />
        <EventRow time="09:38:55" code="EVT-191" text="Quality hold released after CCP-3 verification" type="ok" />
      </div>
    </div>);

}

function KPI({ label, value, unit, delta, status, big }) {
  const color = status === 'warn' ? 'var(--kt-warning)' : status === 'bad' ? 'var(--kt-danger)' : 'var(--kt-cyan-400)';
  return (
    <div className={`kt-kpi ${big ? 'kt-kpi-big' : ''}`}>
      <div className="kt-kpi-label">{label}</div>
      <div className="kt-kpi-value">
        <span style={{ color: '#fff' }}>{value}</span>
        <span className="kt-kpi-unit">{unit}</span>
      </div>
      <div className="kt-kpi-delta" style={{ color }}>
        <span>{delta}</span>
      </div>
    </div>);

}

function Sparkline({ data, target }) {
  const w = 360,h = 60;
  const min = Math.min(...data) - 1;
  const max = Math.max(...data) + 1;
  const pts = data.map((v, i) => {
    const x = i / (data.length - 1) * w;
    const y = h - (v - min) / (max - min) * h;
    return [x, y];
  });
  const path = pts.map((p, i) => i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`).join(' ');
  const area = path + ` L${w},${h} L0,${h} Z`;
  const targetY = h - (target - min) / (max - min) * h;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: '100%', height: 60, display: 'block' }}>
      <defs>
        <linearGradient id="sparkFill" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="var(--kt-cyan-500)" stopOpacity="0.35" />
          <stop offset="100%" stopColor="var(--kt-cyan-500)" stopOpacity="0" />
        </linearGradient>
      </defs>
      <line x1="0" y1={targetY} x2={w} y2={targetY} stroke="var(--kt-cyan-400)" strokeWidth="1" strokeDasharray="2,4" opacity="0.6" />
      <path d={area} fill="url(#sparkFill)" />
      <path d={path} fill="none" stroke="var(--kt-cyan-400)" strokeWidth="1.5" />
      {pts.length > 0 &&
      <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="3" fill="#fff" stroke="var(--kt-cyan-500)" strokeWidth="1.5" />
      }
    </svg>);

}

function EventRow({ time, code, text, type }) {
  const dot = type === 'ok' ? 'var(--kt-success)' : type === 'warn' ? 'var(--kt-warning)' : 'var(--kt-cyan-400)';
  return (
    <div className="kt-hero-event">
      <span className="kt-mono" style={{ color: 'var(--kt-navy-400)', fontSize: 11, minWidth: 64 }}>{time}</span>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: dot, flexShrink: 0 }}></span>
      <span className="kt-mono" style={{ color: 'var(--kt-navy-200)', fontSize: 11, minWidth: 60 }}>{code}</span>
      <span style={{ color: 'var(--kt-navy-100)', fontSize: 12 }}>{text}</span>
    </div>);

}

/* ── Variant B: ISA-95 architecture diagram ───────────────── */
function ArchitectureDiagram() {
  const layers = [
  { id: 'L4', label: 'L4 · Business Planning', items: ['ERP', 'PLM', 'BI'], color: 'var(--kt-navy-600)' },
  { id: 'L3', label: 'L3 · MES / MOM', items: ['TrakSYS', 'Workflow', 'Genealogy'], color: 'var(--kt-cyan-500)', highlight: true },
  { id: 'L2', label: 'L2 · Supervisory Control', items: ['SCADA', 'HMI', 'Historian'], color: 'var(--kt-cyan-600)' },
  { id: 'L1', label: 'L1 · Sensing & Manipulation', items: ['PLC', 'OPC UA', 'MQTT'], color: 'var(--kt-cyan-800)' },
  { id: 'L0', label: 'L0 · Physical Process', items: ['Sensors', 'Actuators', 'Lines'], color: 'var(--kt-navy-900)' }];

  return (
    <div className="kt-hero-tile">
      <div className="kt-hero-tile-chrome">
        <div className="kt-hero-tile-chrome-left">
          <span className="kt-hero-tile-dot"></span>
          <span className="kt-mono" style={{ fontSize: 11, letterSpacing: '0.1em', color: 'var(--kt-navy-200)' }}>
            ISA-95 · OPERATIONAL ARCHITECTURE
          </span>
        </div>
        <span className="kt-mono" style={{ fontSize: 11, color: 'var(--kt-navy-400)' }}>SCHEMA v.2.1</span>
      </div>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {layers.map((layer) =>
        <div key={layer.id} className="kt-arch-layer" style={{
          display: 'grid',
          gridTemplateColumns: '80px 1fr',
          alignItems: 'center',
          gap: 16,
          padding: '14px 16px',
          background: layer.highlight ? 'rgba(0,184,212,0.12)' : 'rgba(255,255,255,0.03)',
          border: `1px solid ${layer.highlight ? 'rgba(0,184,212,0.4)' : 'rgba(255,255,255,0.08)'}`,
          borderRadius: 6
        }}>
            <span className="kt-mono" style={{
            fontSize: 11,
            letterSpacing: '0.1em',
            color: layer.highlight ? 'var(--kt-cyan-400)' : 'var(--kt-navy-200)',
            fontWeight: 700
          }}>{layer.id}</span>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
              <span style={{ color: '#fff', fontSize: 13, fontWeight: 600 }}>{layer.label.replace(layer.id + ' · ', '')}</span>
              <div style={{ display: 'flex', gap: 6 }}>
                {layer.items.map((item) =>
              <span key={item} className="kt-mono" style={{
                fontSize: 10,
                padding: '3px 8px',
                background: layer.highlight ? 'rgba(0,184,212,0.2)' : 'rgba(255,255,255,0.05)',
                color: layer.highlight ? 'var(--kt-cyan-200)' : 'var(--kt-navy-200)',
                borderRadius: 3,
                letterSpacing: '0.05em'
              }}>{item}</span>
              )}
              </div>
            </div>
          </div>
        )}
      </div>
      <div style={{
        padding: '14px 24px',
        borderTop: '1px solid rgba(255,255,255,0.08)',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <span className="kt-mono" style={{ fontSize: 10, color: 'var(--kt-navy-400)', letterSpacing: '0.1em' }}>
          KAIZEN TECH SCOPE: L1 → L4 INTEGRATION + L3 IMPLEMENTATION
        </span>
        <span className="kt-mono" style={{ fontSize: 10, color: 'var(--kt-cyan-400)' }}>● ACTIVE</span>
      </div>
    </div>);

}

/* ── Variant C: Shopfloor photo placeholder ───────────────── */
function ShopfloorPhoto() {
  return (
    <div className="kt-hero-tile" style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{
        position: 'relative',
        aspectRatio: '4/3',
        background: 'linear-gradient(135deg, #0A1628 0%, #1E3A5F 100%)',
        backgroundImage: 'url(https://images.unsplash.com/photo-1565939733948-1bbe05a9e689?auto=format&fit=crop&w=1200&q=80)',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        filter: 'saturate(0.8) brightness(0.85) hue-rotate(-5deg)'
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, rgba(10,22,40,0.2) 0%, rgba(10,22,40,0.7) 100%)'
        }}></div>
        <div style={{ position: 'absolute', top: 16, left: 20, display: 'flex', alignItems: 'center', gap: 10 }}>
          <span className="kt-hero-tile-dot"></span>
          <span className="kt-mono" style={{ fontSize: 11, letterSpacing: '0.1em', color: '#fff' }}>
            SHOPFLOOR · IN OPERATION
          </span>
        </div>
        <div style={{ position: 'absolute', bottom: 24, left: 24, right: 24 }}>
          <div className="kt-mono" style={{ fontSize: 11, color: 'var(--kt-cyan-400)', letterSpacing: '0.1em', marginBottom: 6 }}>
            FROM SENSOR TO DECISION
          </div>
          <div style={{ color: '#fff', fontSize: 22, fontWeight: 700, lineHeight: 1.2 }}>
            Where operational systems meet the line.
          </div>
        </div>
      </div>
      <div style={{ padding: 20, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
        <MiniStat label="SITES LIVE" value="42" unit="" />
        <MiniStat label="TRAKSYS DEPLOYS" value="28" unit="" />
        <MiniStat label="UPTIME 90D" value="99.7" unit="%" />
      </div>
    </div>);

}

function MiniStat({ label, value, unit }) {
  return (
    <div>
      <div className="kt-mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--kt-navy-200)', marginBottom: 6 }}>{label}</div>
      <div style={{ color: '#fff', fontFamily: 'var(--kt-font-mono)', fontSize: 22, fontWeight: 600 }}>
        {value}<span style={{ fontSize: 14, color: 'var(--kt-cyan-400)', marginLeft: 2 }}>{unit}</span>
      </div>
    </div>);

}

function Hero({ tweaks }) {
  const v = HEADLINE_VARIANTS[tweaks.headline] || HEADLINE_VARIANTS.shopfloor;
  const VisualMap = {
    dashboard: LiveDashboardTile,
    architecture: ArchitectureDiagram,
    shopfloor: ShopfloorPhoto
  };
  const Visual = VisualMap[tweaks.heroVisual] || LiveDashboardTile;

  return (
    <section className="kt-hero">
      <div className="kt-hero-bg-grid"></div>
      <div className="kt-container kt-hero-inner">
        <div className="kt-hero-copy">
          <HeroEyebrow />
          <h1 className="kt-hero-title">
            {v.title.map((line, i) =>
            <span key={i} className={i === v.title.length - 1 ? 'kt-hero-title-accent' : ''}>
                {line}<br />
              </span>
            )}
          </h1>
          <p className="kt-hero-sub">{v.sub}</p>
          <HeroCTA />
          <div className="kt-hero-meta">
            <div>
              <div className="kt-hero-meta-num">42</div>
              <div className="kt-hero-meta-label">Sites delivered<br />across EU, US & Africa</div>
            </div>
            <div>
              <div className="kt-hero-meta-num">25<span style={{ color: 'var(--kt-cyan-500)' }}>+</span></div>
              <div className="kt-hero-meta-label">Single-instance<br />multi-site template</div>
            </div>
            <div>
              <div className="kt-hero-meta-num">11<span style={{ fontSize: '0.6em' }}>yrs</span></div>
              <div className="kt-hero-meta-label">Of MES/MOM<br />implementation</div>
            </div>
          </div>
        </div>
        <div className="kt-hero-visual">
          <Visual />
        </div>
      </div>
    </section>);

}

window.Hero = Hero;