/* global React */
const { useState, useEffect, useRef } = React;

// ── Phone frame ───────────────────────────────────────────────────────────────
function PhoneFrame({ children }) {
  return (
    <div style={{
      width: 240, height: 480,
      background: "oklch(0.12 0.03 250)",
      borderRadius: 36,
      border: "6px solid oklch(0.22 0.04 250)",
      boxShadow: "0 0 0 1px oklch(0.30 0.04 250), 0 40px 80px -20px oklch(0.10 0.04 250 / 0.6), inset 0 1px 0 oklch(0.35 0.04 250)",
      position: "relative",
      overflow: "hidden",
      flexShrink: 0,
    }}>
      {/* notch */}
      <div style={{ position:"absolute", top:0, left:"50%", transform:"translateX(-50%)", width:72, height:22, background:"oklch(0.12 0.03 250)", borderRadius:"0 0 14px 14px", zIndex:10 }} />
      {/* status bar */}
      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"6px 18px 0", fontSize:9, fontFamily:"var(--font-mono)", color:"oklch(0.65 0.03 240)", position:"relative", zIndex:5 }}>
        <span>9:41</span>
        <span>●●● ▲</span>
      </div>
      <div style={{ position:"absolute", inset:0, top:28, overflowY:"hidden" }}>{children}</div>
      {/* home bar */}
      <div style={{ position:"absolute", bottom:8, left:"50%", transform:"translateX(-50%)", width:80, height:4, background:"oklch(0.35 0.03 250)", borderRadius:2 }} />
    </div>
  );
}

// ── Browser frame ─────────────────────────────────────────────────────────────
function BrowserFrame({ children, url = "app.gropp.tech" }) {
  return (
    <div style={{
      width: 420, height: 300,
      background: "oklch(0.97 0.005 240)",
      borderRadius: 10,
      border: "1px solid oklch(0.82 0.02 240)",
      boxShadow: "0 30px 70px -20px oklch(0.50 0.06 240 / 0.22)",
      overflow: "hidden",
      flexShrink: 0,
    }}>
      {/* chrome */}
      <div style={{ background:"oklch(0.94 0.006 240)", borderBottom:"1px solid oklch(0.86 0.01 240)", padding:"8px 12px", display:"flex", alignItems:"center", gap:8 }}>
        <div style={{ display:"flex", gap:5 }}>
          {["oklch(0.70 0.15 25)","oklch(0.75 0.15 80)","oklch(0.65 0.18 145)"].map((c,i) => (
            <div key={i} style={{ width:10, height:10, borderRadius:"50%", background:c }} />
          ))}
        </div>
        <div style={{ flex:1, background:"oklch(0.97 0.005 240)", border:"1px solid oklch(0.86 0.01 240)", borderRadius:4, padding:"3px 10px", fontFamily:"var(--font-mono)", fontSize:9.5, color:"oklch(0.55 0.03 240)", letterSpacing:"0.04em" }}>
          {url}
        </div>
      </div>
      <div style={{ height:"calc(100% - 37px)", overflow:"hidden" }}>{children}</div>
    </div>
  );
}

// ── Screen mocks ──────────────────────────────────────────────────────────────
function AppScreen({ isEs }) {
  const [step, setStep] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setStep(s => (s + 1) % 4), 2200);
    return () => clearInterval(id);
  }, []);
  const tasks = [
    { label: isEs ? "Retirar paquetes en bodega" : "Pick up packages at depot", done: true },
    { label: isEs ? "Entregar — Av. Italia 3421" : "Deliver — Av. Italia 3421", done: step > 0 },
    { label: isEs ? "Entregar — Br. Artigas 880" : "Deliver — Br. Artigas 880", done: step > 1 },
    { label: isEs ? "Entregar — Malvín Norte" : "Deliver — Malvín Norte", done: step > 2 },
  ];
  return (
    <div style={{ height:"100%", background:"oklch(0.13 0.03 250)", display:"flex", flexDirection:"column" }}>
      {/* map area */}
      <div style={{ height:140, background:"oklch(0.20 0.04 240)", position:"relative", overflow:"hidden" }}>
        <svg viewBox="0 0 240 140" style={{ width:"100%", height:"100%" }}>
          {/* road grid */}
          {[30,60,90,110].map((y,i) => <line key={`h${i}`} x1={0} y1={y} x2={240} y2={y} stroke="oklch(0.28 0.03 240)" strokeWidth={i===1?2.5:1} />)}
          {[40,80,120,160,200].map((x,i) => <line key={`v${i}`} x1={x} y1={0} x2={x} y2={140} stroke="oklch(0.28 0.03 240)" strokeWidth={1} />)}
          {/* route */}
          <polyline points="40,110 40,60 120,60 120,30 200,30" fill="none" stroke="var(--accent)" strokeWidth={2.5} strokeLinecap="round" strokeDasharray="4 3">
            <animate attributeName="stroke-dashoffset" from="0" to="-14" dur="1s" repeatCount="indefinite" />
          </polyline>
          {/* stops */}
          {[[40,110],[120,60],[200,30]].map(([x,y],i) => (
            <g key={i}>
              <circle cx={x} cy={y} r={i===0?6:5} fill={i===0?"var(--accent)":"oklch(0.60 0.12 50)"} />
              <text x={x+8} y={y+3} fontSize={7} fontFamily="var(--font-mono)" fill="oklch(0.8 0.02 240)">{i+1}</text>
            </g>
          ))}
          {/* current marker */}
          <circle cx={40} cy={110} r={10} fill="var(--accent)" opacity={0.15}>
            <animate attributeName="r" values="8;14;8" dur="2s" repeatCount="indefinite" />
            <animate attributeName="opacity" values="0.2;0;0.2" dur="2s" repeatCount="indefinite" />
          </circle>
          <text x={8} y={128} fontSize={7.5} fontFamily="var(--font-mono)" fill="oklch(0.55 0.03 240)">ETA 14:32 · 3.2 km</text>
        </svg>
      </div>
      {/* tasks */}
      <div style={{ flex:1, padding:"10px 14px", display:"flex", flexDirection:"column", gap:6 }}>
        <div style={{ fontFamily:"var(--font-mono)", fontSize:8, color:"oklch(0.45 0.04 240)", letterSpacing:"0.1em", marginBottom:2 }}>
          {isEs ? "PARADAS HOY" : "TODAY'S STOPS"} · {tasks.filter(t=>t.done).length}/{tasks.length}
        </div>
        {tasks.map((t, i) => (
          <div key={i} style={{ display:"flex", alignItems:"center", gap:8, opacity: t.done ? 0.45 : 1, transition:"opacity .4s" }}>
            <div style={{ width:14, height:14, borderRadius:"50%", border:`1.5px solid ${t.done ? "oklch(0.62 0.18 145)" : "var(--accent)"}`, display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0 }}>
              {t.done && <div style={{ width:6, height:6, borderRadius:"50%", background:"oklch(0.62 0.18 145)" }} />}
            </div>
            <div style={{ fontSize:10, color: t.done ? "oklch(0.45 0.03 240)" : "oklch(0.88 0.02 240)", textDecoration: t.done ? "line-through" : "none", transition:"all .4s" }}>{t.label}</div>
          </div>
        ))}
        {/* voice bar */}
        <div style={{ marginTop:"auto", background:"var(--accent)", borderRadius:8, padding:"8px 12px", display:"flex", alignItems:"center", gap:8 }}>
          <div style={{ display:"flex", alignItems:"center", gap:2, height:16 }}>
            {[4,8,12,8,5,10,7].map((h,i) => (
              <div key={i} style={{ width:2, height:h, borderRadius:1, background:"rgba(255,255,255,0.7)",
                animation:`appBar ${0.5+i*0.1}s ease-in-out infinite alternate`, animationDelay:`${i*0.08}s` }} />
            ))}
            <style>{`@keyframes appBar{from{transform:scaleY(.3)}to{transform:scaleY(1)}}`}</style>
          </div>
          <div style={{ fontSize:10, color:"rgba(255,255,255,0.9)", fontWeight:500 }}>{isEs ? "Hablar con AI…" : "Talk to AI…"}</div>
        </div>
      </div>
    </div>
  );
}

function WebScreen({ isEs }) {
  const [tick, setTick] = useState(0);
  useEffect(() => { const id = setInterval(() => setTick(t => t+1), 1800); return () => clearInterval(id); }, []);
  const drivers = [
    { name:"J. Pérez",  stops:12, done:8,  status:"on-route", eta:"14:32" },
    { name:"M. Alves",  stops:9,  done:9,  status:"done",     eta:"—" },
    { name:"C. Soria",  stops:14, done:5,  status:"delayed",  eta:"15:10" },
    { name:"R. Torres", stops:11, done:7,  status:"on-route", eta:"14:48" },
  ];
  const statusColor = { "on-route": "oklch(0.62 0.18 145)", "done": "oklch(0.55 0.04 240)", "delayed": "oklch(0.65 0.18 35)" };
  return (
    <div style={{ height:"100%", display:"grid", gridTemplateColumns:"130px 1fr", background:"oklch(0.97 0.005 240)" }}>
      {/* sidebar */}
      <div style={{ background:"oklch(0.14 0.03 250)", borderRight:"1px solid oklch(0.22 0.03 250)", padding:"12px 0", display:"flex", flexDirection:"column", gap:2 }}>
        {[
          { label: isEs ? "Mapa en vivo" : "Live map", active: true },
          { label: isEs ? "Conductores" : "Drivers", active: false },
          { label: isEs ? "Rutas" : "Routes", active: false },
          { label: isEs ? "Alertas" : "Alerts", active: false },
          { label: "Analytics", active: false },
        ].map((item, i) => (
          <div key={i} style={{ padding:"6px 14px", fontSize:10, fontFamily:"var(--font-mono)", color: item.active ? "var(--accent)" : "oklch(0.45 0.03 240)", background: item.active ? "oklch(0.20 0.05 250)" : "transparent", borderLeft: item.active ? "2px solid var(--accent)" : "2px solid transparent", letterSpacing:"0.04em" }}>
            {item.label}
          </div>
        ))}
      </div>
      {/* main */}
      <div style={{ display:"flex", flexDirection:"column", overflow:"hidden" }}>
        {/* map */}
        <div style={{ height:130, background:"oklch(0.20 0.04 240)", position:"relative" }}>
          <svg viewBox="0 0 290 130" style={{ width:"100%", height:"100%" }}>
            {[20,45,70,95].map(y => <line key={y} x1={0} y1={y} x2={290} y2={y} stroke="oklch(0.27 0.03 240)" strokeWidth={1} />)}
            {[40,80,120,160,200,240].map(x => <line key={x} x1={x} y1={0} x2={x} y2={130} stroke="oklch(0.27 0.03 240)" strokeWidth={1} />)}
            {/* routes */}
            <polyline points="40,95 80,70 120,45 160,45" fill="none" stroke="var(--accent)" strokeWidth={1.8} strokeLinecap="round" opacity={0.8} />
            <polyline points="80,95 120,70 160,95 200,70" fill="none" stroke="oklch(0.62 0.18 145)" strokeWidth={1.8} strokeLinecap="round" opacity={0.8} />
            <polyline points="40,45 80,20 120,45 200,20 240,45" fill="none" stroke="oklch(0.65 0.18 35)" strokeWidth={1.8} strokeLinecap="round" opacity={0.8} />
            {/* vehicles */}
            {[[40+(tick%8)*14, 95-(tick%8)*3.5],[80+(tick%6)*10,95-(tick%6)*4.2],[40+(tick%9)*22,45+(tick%9)*0]].map(([x,y],i) => (
              <circle key={i} cx={x} cy={y} r={5} fill={["var(--accent)","oklch(0.62 0.18 145)","oklch(0.65 0.18 35)"][i]} />
            ))}
          </svg>
        </div>
        {/* drivers table */}
        <div style={{ flex:1, padding:"6px 10px", overflowY:"hidden" }}>
          <div style={{ fontFamily:"var(--font-mono)", fontSize:7.5, color:"oklch(0.45 0.03 240)", letterSpacing:"0.1em", marginBottom:4, display:"grid", gridTemplateColumns:"1fr 60px 60px 50px", gap:4 }}>
            <span>{isEs ? "CONDUCTOR" : "DRIVER"}</span><span>{isEs ? "PARADAS" : "STOPS"}</span><span>STATUS</span><span>ETA</span>
          </div>
          {drivers.map((d, i) => (
            <div key={i} style={{ display:"grid", gridTemplateColumns:"1fr 60px 60px 50px", gap:4, padding:"4px 0", borderBottom:"1px solid oklch(0.90 0.005 240)", alignItems:"center" }}>
              <span style={{ fontSize:10, fontWeight:500 }}>{d.name}</span>
              <span style={{ fontFamily:"var(--font-mono)", fontSize:9, color:"var(--fog)" }}>{d.done}/{d.stops}</span>
              <span style={{ fontFamily:"var(--font-mono)", fontSize:8, color:statusColor[d.status] }}>{d.status}</span>
              <span style={{ fontFamily:"var(--font-mono)", fontSize:9, color:"var(--fog)" }}>{d.eta}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function SupervisorScreen({ isEs }) {
  const [selected, setSelected] = useState(0);
  const drivers = [
    { name:"J. Pérez",  score:91, trend:"+3", incidents:0 },
    { name:"C. Soria",  score:74, trend:"−5", incidents:2 },
    { name:"R. Torres", score:83, trend:"+1", incidents:1 },
    { name:"M. Alves",  score:96, trend:"+2", incidents:0 },
  ];
  const scoreColor = s => s >= 85 ? "oklch(0.62 0.18 145)" : s >= 70 ? "oklch(0.72 0.16 75)" : "oklch(0.65 0.18 35)";
  const d = drivers[selected];
  return (
    <div style={{ height:"100%", display:"grid", gridTemplateColumns:"140px 1fr", background:"oklch(0.97 0.005 240)" }}>
      {/* driver list */}
      <div style={{ borderRight:"1px solid oklch(0.88 0.01 240)", overflowY:"hidden" }}>
        <div style={{ padding:"8px 10px", fontFamily:"var(--font-mono)", fontSize:7.5, color:"oklch(0.45 0.03 240)", letterSpacing:"0.1em", borderBottom:"1px solid oklch(0.88 0.01 240)" }}>
          {isEs ? "CONDUCTORES" : "DRIVERS"} · {drivers.length}
        </div>
        {drivers.map((dr, i) => (
          <div key={i} onClick={() => setSelected(i)} style={{ padding:"8px 10px", cursor:"pointer", background: i === selected ? "oklch(0.93 0.01 240)" : "transparent", borderBottom:"1px solid oklch(0.92 0.005 240)" }}>
            <div style={{ fontSize:10, fontWeight:500, marginBottom:2 }}>{dr.name}</div>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center" }}>
              <span style={{ fontFamily:"var(--font-mono)", fontSize:12, fontWeight:600, color:scoreColor(dr.score) }}>{dr.score}</span>
              <span style={{ fontFamily:"var(--font-mono)", fontSize:8, color: dr.trend.startsWith("+") ? "oklch(0.62 0.18 145)" : "oklch(0.65 0.18 35)" }}>{dr.trend}</span>
            </div>
          </div>
        ))}
      </div>
      {/* detail */}
      <div style={{ padding:"10px 14px", display:"flex", flexDirection:"column", gap:8 }}>
        <div style={{ display:"flex", alignItems:"center", gap:8 }}>
          <div style={{ width:28, height:28, borderRadius:"50%", background:"var(--accent)", display:"flex", alignItems:"center", justifyContent:"center", color:"white", fontWeight:600, fontSize:11 }}>{d.name[0]}</div>
          <div>
            <div style={{ fontWeight:500, fontSize:12 }}>{d.name}</div>
            <div style={{ fontFamily:"var(--font-mono)", fontSize:7.5, color:"oklch(0.50 0.03 240)", letterSpacing:"0.06em" }}>{isEs ? "SCORE SEMANA" : "WEEKLY SCORE"}</div>
          </div>
          <div style={{ marginLeft:"auto", fontFamily:"var(--font-mono)", fontSize:22, fontWeight:600, color:scoreColor(d.score) }}>{d.score}</div>
        </div>
        {/* mini score bar */}
        <div style={{ background:"oklch(0.90 0.01 240)", borderRadius:4, height:5, overflow:"hidden" }}>
          <div style={{ width:`${d.score}%`, height:"100%", background:scoreColor(d.score), borderRadius:4, transition:"width .5s" }} />
        </div>
        {/* incidents */}
        <div style={{ fontFamily:"var(--font-mono)", fontSize:8, color:"oklch(0.45 0.03 240)", letterSpacing:"0.08em", marginTop:2 }}>
          {isEs ? "INCIDENTES" : "INCIDENTS"} · {d.incidents > 0 ? d.incidents : (isEs ? "ninguno" : "none")}
        </div>
        {d.incidents > 0 && (
          <div style={{ background:"oklch(0.97 0.03 35)", border:"1px solid oklch(0.88 0.08 35)", borderRadius:6, padding:"6px 10px", fontSize:9, color:"oklch(0.50 0.12 35)", fontFamily:"var(--font-mono)" }}>
            ⚠ {isEs ? "Frenado brusco 14:02 · video disponible" : "Hard braking 14:02 · video available"}
          </div>
        )}
        {/* coaching prompt */}
        <div style={{ marginTop:"auto", background:"oklch(0.94 0.01 240)", borderRadius:6, padding:"7px 10px", fontSize:9, color:"oklch(0.40 0.03 240)", lineHeight:1.4 }}>
          <span style={{ fontFamily:"var(--font-mono)", fontSize:7.5, color:"var(--accent)", letterSpacing:"0.1em" }}>AI · </span>
          {isEs ? "Mejorar freno en curvas. Recomendamos sesión de coaching esta semana." : "Improve braking in curves. We recommend a coaching session this week."}
        </div>
      </div>
    </div>
  );
}

// ── Main PlatformSection ──────────────────────────────────────────────────────
function PlatformSection({ copy, lang }) {
  const [active, setActive] = useState(0);
  const isEs = lang === "es";
  const tabs = copy.tabs;
  const tab = tabs[active];

  const deviceType = ["phone", "browser", "browser"][active];

  return (
    <section className="plat-section" id="platform">
      <style>{`
        .plat-section { padding: 100px 0; background: var(--bone); border-bottom: 1px solid var(--line-soft); }

        .plat-head { display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 56px; gap: 40px; flex-wrap: wrap; }
        .plat-head h2 { font-size: clamp(30px, 3.8vw, 56px); letter-spacing: -0.025em; font-weight: 500; line-height: 1.04; max-width: 520px; }
        .plat-head h2 .accent { color: var(--accent); }
        .plat-head-sub { font-size: 15px; line-height: 1.6; color: var(--fog); max-width: 340px; }

        .plat-tabs { display: flex; gap: 0; border: 1px solid var(--line); border-radius: 8px; overflow: hidden; margin-bottom: 56px; width: fit-content; }
        .plat-tab { padding: 10px 24px; font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.10em; cursor: pointer; border: none; background: transparent; color: var(--mist); transition: all .2s; position: relative; }
        .plat-tab:not(:last-child) { border-right: 1px solid var(--line); }
        .plat-tab.active { background: var(--ink); color: var(--bone); }
        .plat-tab-role { font-size: 8.5px; display: block; opacity: 0.6; margin-top: 2px; letter-spacing: 0.14em; }

        .plat-body { display: grid; grid-template-columns: 1fr 1fr; gap: 72px; align-items: center; }
        .plat-body.phone-layout { grid-template-columns: 1fr auto; }

        .plat-features { display: flex; flex-direction: column; gap: 28px; }
        .plat-tag { font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.14em; color: var(--accent); background: color-mix(in oklch, var(--accent) 10%, transparent); border: 1px solid var(--accent); padding: 4px 10px; border-radius: 999px; display: inline-block; margin-bottom: 6px; }
        .plat-features h3 { font-size: clamp(22px, 2.8vw, 36px); letter-spacing: -0.02em; font-weight: 500; line-height: 1.1; margin-bottom: 10px; }
        .plat-features h3 .accent { color: var(--accent); }
        .plat-features-sub { font-size: 15px; color: var(--fog); line-height: 1.6; margin-bottom: 20px; }
        .plat-feat-list { display: flex; flex-direction: column; gap: 14px; }
        .plat-feat { display: flex; gap: 12px; align-items: flex-start; }
        .plat-feat-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); flex-shrink: 0; margin-top: 6px; }
        .plat-feat-body { }
        .plat-feat-title { font-size: 14px; font-weight: 500; margin-bottom: 2px; }
        .plat-feat-desc { font-size: 13px; color: var(--fog); line-height: 1.45; }

        .plat-device { display: flex; justify-content: center; align-items: center; }
        .plat-device-wrap { position: relative; }
        .plat-device-glow { position: absolute; inset: -40px; background: radial-gradient(50% 50% at 50% 50%, color-mix(in oklch, var(--accent) 15%, transparent), transparent 70%); pointer-events: none; }

        @media (max-width: 900px) {
          .plat-body { grid-template-columns: 1fr !important; gap: 40px; }
          .plat-device { order: -1; }
        }
      `}</style>

      <div className="container">
        <div className="plat-head">
          <h2>{copy.title_a}<span className="accent">{copy.title_b}</span>{copy.title_c}</h2>
          <p className="plat-head-sub">{copy.sub}</p>
        </div>

        {/* Tab switcher */}
        <div className="plat-tabs">
          {tabs.map((t, i) => (
            <button key={i} className={`plat-tab ${i === active ? "active" : ""}`} onClick={() => setActive(i)}>
              {t.tab}
              <span className="plat-tab-role">{t.role}</span>
            </button>
          ))}
        </div>

        {/* Body */}
        <div className={`plat-body ${deviceType === "phone" ? "phone-layout" : ""}`}>
          {/* Features */}
          <div className="plat-features" key={active} style={{ animation: "daiFadeIn .35s ease" }}>
            <div>
              <span className="plat-tag mono">{tab.tag}</span>
              <h3>{tab.title_a}<span className="accent">{tab.title_b}</span>{tab.title_c}</h3>
              <p className="plat-features-sub">{tab.sub}</p>
            </div>
            <div className="plat-feat-list">
              {tab.features.map((f, i) => (
                <div key={i} className="plat-feat">
                  <div className="plat-feat-dot" />
                  <div className="plat-feat-body">
                    <div className="plat-feat-title">{f.title}</div>
                    <div className="plat-feat-desc">{f.body}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Device */}
          <div className="plat-device" key={`d-${active}`} style={{ animation: "daiFadeIn .4s ease" }}>
            <div className="plat-device-wrap">
              <div className="plat-device-glow" />
              {deviceType === "phone"
                ? <PhoneFrame><AppScreen isEs={isEs} /></PhoneFrame>
                : active === 1
                  ? <BrowserFrame url="flow.gropp.tech"><WebScreen isEs={isEs} /></BrowserFrame>
                  : <BrowserFrame url="supervisor.gropp.tech"><SupervisorScreen isEs={isEs} /></BrowserFrame>
              }
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.PlatformSection = PlatformSection;
