
// ─── THEME ────────────────────────────────────────────────────────────────────
const T = {
  bg: "#07090f", surface: "#0c0f1a", card: "#101420", cardHover: "#141829",
  border: "#1a2236", borderLight: "#202c42",
  blue: "#2563eb",
  accent: "#38bdf8", accentGlow: "#38bdf814", accent2: "#818cf8",
  accent3: "#34d399", gold: "#f59e0b", goldGlow: "#f59e0b18",
  warn: "#fbbf24", danger: "#f87171",
  text: "#eef2ff", textMid: "#94a3b8", textMuted: "#3d5068",
  input: "#080b14", inputBorder: "#1a2236",
  mono: "'JetBrains Mono','Cascadia Code',monospace",
  sans: "'DM Sans',system-ui,sans-serif",
};

const APP_MAX_W = 1080;

function isValidLicenseKeyFormat(key) {
  const k = String(key || "").trim().toUpperCase();
  return k.length >= 8 && k.length <= 80 && /^[A-Z0-9-]+$/.test(k);
}

// ─── MCU PROFILES ─────────────────────────────────────────────────────────────
const BETA_LICENSE_PUBLIC = "REGCALC-BETA-2026";

function getEngine() {
  return window.RegCalcEngine || null;
}
function getMcuProfiles() {
  return getEngine()?.MCU_PROFILES || {};
}
function sdkExportTitle(profile, base) {
  const sdk = profile?.codeSdk || "SDK";
  return `${sdk} Export — ${base}`;
}

// ─── HELPERS ──────────────────────────────────────────────────────────────────
const fmtHz   = (n, d=3) => { if(!isFinite(n)||isNaN(n)||n<=0)return"—"; if(n>=1e9)return(n/1e9).toFixed(d)+" GHz"; if(n>=1e6)return(n/1e6).toFixed(d)+" MHz"; if(n>=1e3)return(n/1e3).toFixed(d)+" kHz"; return n.toFixed(d)+" Hz"; };
const fmtTime = s => { if(!isFinite(s)||isNaN(s)||s<=0)return"—"; if(s<1e-9)return(s*1e12).toFixed(2)+" ps"; if(s<1e-6)return(s*1e9).toFixed(2)+" ns"; if(s<1e-3)return(s*1e6).toFixed(2)+" µs"; if(s<1)return(s*1e3).toFixed(2)+" ms"; return s.toFixed(4)+" s"; };
const clamp   = (v,mn,mx) => Math.min(Math.max(v,mn),mx);
const ts      = () => new Date().toLocaleTimeString([], {hour:'2-digit',minute:'2-digit'});

// ─── SHARE URL HELPERS ────────────────────────────────────────────────────────
const encodeShare = (tab, mcu, params) => {
  const p = new URLSearchParams({ calc: tab, mcu, ...params });
  return `${window.location.origin}${window.location.pathname}?${p}`;
};

const HISTORY_STORAGE_KEY = "regcalc_history_v1";
const TAB_LABELS = { baud: "UART", uart: "UART", timer: "Timer", pll: "PLL", pwm: "PWM", adc: "ADC", bus: "I²C/SPI" };

function normalizeHistoryTab(tab) {
  if (tab === "uart") return "baud";
  return tab;
}

function mcuKeyFromProfileName(name) {
  return Object.entries(getMcuProfiles()).find(([, v]) => v.name === name)?.[0] || null;
}

function useRestoreInputs(restoreSnap, tabId, apply, onRestored) {
  useEffect(() => {
    if (!restoreSnap || restoreSnap.tab !== tabId) return;
    apply(restoreSnap.inputs || {});
    onRestored?.();
  }, [restoreSnap?.nonce]);
}

// ─── UI PRIMITIVES ────────────────────────────────────────────────────────────
const Field = ({ label, value, onChange, unit, placeholder="0", hint }) => (
  <div style={{display:"flex",flexDirection:"column",gap:5}}>
    <label style={{fontSize:10,color:T.textMuted,letterSpacing:"0.12em",textTransform:"uppercase",fontFamily:T.sans,fontWeight:600}}>{label}</label>
    <div style={{display:"flex",alignItems:"center",background:T.input,border:`1px solid ${T.inputBorder}`,borderRadius:7,overflow:"hidden"}}>
      <input type="number" value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder}
        style={{flex:1,minWidth:0,background:"transparent",border:"none",outline:"none",color:T.text,padding:"10px 14px",fontSize:14,fontFamily:T.mono}}/>
      {unit && <span style={{padding:"0 12px",color:T.textMuted,fontSize:11,borderLeft:`1px solid ${T.border}`,alignSelf:"stretch",display:"flex",alignItems:"center"}}>{unit}</span>}
    </div>
    {hint && <span style={{fontSize:10,color:T.textMuted,fontFamily:T.sans}}>{hint}</span>}
  </div>
);

const Sel = ({ label, value, onChange, options }) => (
  <div style={{display:"flex",flexDirection:"column",gap:5}}>
    {label && <label style={{fontSize:10,color:T.textMuted,letterSpacing:"0.12em",textTransform:"uppercase",fontFamily:T.sans,fontWeight:600}}>{label}</label>}
    <select value={value} onChange={e=>onChange(e.target.value)}
      style={{background:T.input,border:`1px solid ${T.inputBorder}`,borderRadius:7,color:T.text,padding:"10px 14px",fontSize:14,outline:"none",fontFamily:T.mono,cursor:"pointer",width:"100%",minWidth:0}}>
      {options.map(o=><option key={o.v} value={o.v}>{o.l}</option>)}
    </select>
  </div>
);

const Res = ({ label, value, highlight, copy, color }) => {
  const [copied, setCopied] = useState(false);
  const c = color||(highlight?T.accent:T.text);
  return (
    <div onClick={()=>{ if(copy){navigator.clipboard?.writeText(String(value)); setCopied(true); setTimeout(()=>setCopied(false),1200); }}}
      style={{background:highlight?T.accentGlow:T.input,border:`1px solid ${highlight?T.accent+"44":T.border}`,borderRadius:7,padding:"9px 14px",display:"flex",justifyContent:"space-between",alignItems:"center",cursor:copy?"pointer":"default",transition:"all 0.15s"}}>
      <span style={{fontSize:11,color:T.textMuted,fontFamily:T.sans}}>{label}{copy&&<span style={{marginLeft:5,opacity:0.5}}>⊕</span>}</span>
      <span style={{fontFamily:T.mono,fontSize:13,color:c,fontWeight:600}}>{copied?"✓ copied":value}</span>
    </div>
  );
};

const Divider = () => <div style={{borderTop:`1px solid ${T.border}`,margin:"2px 0"}}/>;
const Warn    = ({ msg }) => <div style={{background:T.warn+"11",border:`1px solid ${T.warn}44`,borderRadius:7,padding:"8px 12px",color:T.warn,fontSize:12,fontFamily:T.sans}}>⚠ {msg}</div>;

// ─── SHARE BUTTON ─────────────────────────────────────────────────────────────
function ShareBtn({ url }) {
  const [copied, setCopied] = useState(false);
  return (
    <button onClick={()=>{ navigator.clipboard?.writeText(url); setCopied(true); setTimeout(()=>setCopied(false),1800); }}
      title="Copy shareable link"
      style={{padding:"6px 12px",background:copied?T.accent3+"22":"transparent",border:`1px solid ${copied?T.accent3:T.border}`,borderRadius:6,color:copied?T.accent3:T.textMuted,cursor:"pointer",fontSize:11,fontFamily:T.sans,display:"flex",alignItems:"center",gap:5,transition:"all .2s"}}>
      {copied?"✓ Link copied!":"🔗 Share"}
    </button>
  );
}

// ─── CODE BLOCK ───────────────────────────────────────────────────────────────
function CodeBlock({ code, title }) {
  const [copied, setCopied] = useState(false);
  return (
    <div style={{background:T.input,border:`1px solid ${T.border}`,borderRadius:8,overflow:"hidden",marginTop:4}}>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"7px 12px",borderBottom:`1px solid ${T.border}`,background:T.surface}}>
        <span style={{fontSize:10,color:T.textMuted,fontFamily:T.mono}}>{title}</span>
        <button onClick={()=>{ navigator.clipboard?.writeText(code); setCopied(true); setTimeout(()=>setCopied(false),1500); }}
          style={{background:copied?T.accent3+"22":"transparent",border:`1px solid ${copied?T.accent3:T.border}`,borderRadius:4,padding:"3px 10px",color:copied?T.accent3:T.textMuted,cursor:"pointer",fontSize:11,fontFamily:T.sans}}>
          {copied?"✓ Copied!":"Copy"}
        </button>
      </div>
      <pre style={{margin:0,padding:"13px 15px",fontSize:11.5,fontFamily:T.mono,color:T.text,overflowX:"auto",lineHeight:1.75}}><code>{code}</code></pre>
    </div>
  );
}

// ─── HISTORY PANEL ────────────────────────────────────────────────────────────
function HistoryDetail({ entry }) {
  if (!entry) return null;
  const rows = entry.ctx ? Object.entries(entry.ctx).filter(([k]) => k !== "calculator") : [];
  return (
    <div style={{borderTop:`1px solid ${T.border}`,padding:"12px 14px",background:T.card,flexShrink:0}}>
      <p style={{fontSize:10,color:T.textMuted,fontFamily:T.sans,textTransform:"uppercase",letterSpacing:"0.1em",marginBottom:8}}>Pregled</p>
      <p style={{fontSize:11,color:T.textMid,fontFamily:T.mono,lineHeight:1.5,marginBottom:10}}>{entry.summary}</p>
      {rows.length > 0 && (
        <div style={{display:"flex",flexDirection:"column",gap:5}}>
          {rows.map(([k, v]) => (
            <div key={k} style={{display:"flex",justifyContent:"space-between",gap:8,fontSize:11,fontFamily:T.mono}}>
              <span style={{color:T.textMuted}}>{k}</span>
              <span style={{color:T.text,textAlign:"right"}}>{String(v)}</span>
            </div>
          ))}
        </div>
      )}
      <p style={{fontSize:10,color:T.accent,fontFamily:T.sans,marginTop:10}}>Klikni stavku da učitaš vrijednosti u kalkulator →</p>
    </div>
  );
}

function HistoryPanel({ history, selectedId, onSelect, onRestore }) {
  if (history.length === 0) return (
    <div style={{padding:"20px 14px",textAlign:"center",color:T.textMuted,fontSize:12,fontFamily:T.sans}}>
      Nema historije.<br/>Kalkulacije se pojavljuju dok radite.
    </div>
  );
  return (
    <div style={{display:"flex",flexDirection:"column",gap:1}}>
      {history.map((h, i) => {
        const tabId = normalizeHistoryTab(h.tab);
        const selected = selectedId === i;
        return (
          <div
            key={`${tabId}-${h.mcu}-${h.summary}-${h.time}-${i}`}
            onClick={() => { onSelect(i, h); onRestore(h); }}
            style={{
              padding:"10px 14px",
              cursor:"pointer",
              borderBottom:`1px solid ${T.border}`,
              background: selected ? T.accent + "14" : "transparent",
              borderLeft: selected ? `3px solid ${T.accent}` : "3px solid transparent",
              transition:"background .15s",
            }}
            onMouseEnter={e => { if (!selected) e.currentTarget.style.background = T.card; }}
            onMouseLeave={e => { if (!selected) e.currentTarget.style.background = "transparent"; }}
          >
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:8}}>
              <div>
                <span style={{fontSize:11,color:T.accent,fontFamily:T.mono,fontWeight:600}}>{TAB_LABELS[tabId] || tabId.toUpperCase()}</span>
                <span style={{fontSize:10,color:T.textMuted,fontFamily:T.mono,marginLeft:6}}>{h.mcu}</span>
              </div>
              <span style={{fontSize:10,color:T.textMuted,fontFamily:T.mono,flexShrink:0}}>{h.time}</span>
            </div>
            <div style={{fontSize:11,color:T.textMid,fontFamily:T.mono,marginTop:3,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{h.summary}</div>
          </div>
        );
      })}
    </div>
  );
}

// ─── EXPORT JSON ──────────────────────────────────────────────────────────────
function ExportModal({ data, onClose }) {
  const [copied, setCopied] = useState(false);
  const json = JSON.stringify(data, null, 2);
  return (
    <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,.75)",backdropFilter:"blur(8px)",zIndex:300,display:"flex",alignItems:"center",justifyContent:"center",padding:16}}>
      <div style={{background:T.surface,border:`1px solid ${T.border}`,borderRadius:14,padding:24,width:"100%",maxWidth:520,maxHeight:"80vh",display:"flex",flexDirection:"column",gap:14}}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
          <h3 style={{fontSize:15,fontWeight:700,fontFamily:T.sans}}>Export Calculation</h3>
          <button onClick={onClose} style={{background:"none",border:"none",color:T.textMuted,cursor:"pointer",fontSize:20,lineHeight:1}}>×</button>
        </div>
        <pre style={{flex:1,overflow:"auto",background:T.input,border:`1px solid ${T.border}`,borderRadius:8,padding:"12px 14px",fontSize:11,fontFamily:T.mono,color:T.text,lineHeight:1.7}}>{json}</pre>
        <div style={{display:"flex",gap:8}}>
          <button onClick={()=>{ navigator.clipboard?.writeText(json); setCopied(true); setTimeout(()=>setCopied(false),1500); }}
            style={{flex:1,padding:"10px",background:copied?T.accent3+"22":T.card,border:`1px solid ${copied?T.accent3:T.border}`,borderRadius:8,color:copied?T.accent3:T.textMid,cursor:"pointer",fontSize:13,fontWeight:600,fontFamily:T.sans}}>
            {copied?"✓ Copied!":"Copy JSON"}
          </button>
          <button onClick={()=>{ const a=document.createElement("a"); a.href="data:text/json,"+encodeURIComponent(json); a.download=`regcalc-${data.calculator||"export"}-${Date.now()}.json`; a.click(); }}
            style={{flex:1,padding:"10px",background:T.blue,border:"none",borderRadius:8,color:"#fff",cursor:"pointer",fontSize:13,fontWeight:600,fontFamily:T.sans}}>
            ↓ Download .json
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── AI ASSISTANT ─────────────────────────────────────────────────────────────
function AIAssistant({ context, licenseKey }) {
  const [open, setOpen] = useState(false);
  const [msgs, setMsgs] = useState([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const bottomRef = useRef(null);
  useEffect(()=>{ bottomRef.current?.scrollIntoView({behavior:"smooth"}); },[msgs]);

  const send = async () => {
    if (!input.trim()||loading) return;
    const userMsg = input.trim(); setInput("");
    setMsgs(m=>[...m,{role:"user",content:userMsg}]); setLoading(true);
    try {
      const history = [...msgs,{role:"user",content:userMsg}].map(m=>({role:m.role,content:m.content}));
      const systemPrompt = `Embedded MCU assistant. Context: ${JSON.stringify(context)}. Answer in 2–6 short sentences. Registers/HAL only when needed. Max ~120 words.`;
      const res = await fetch("/api/ai-assistant",{
        method:"POST",
        credentials:"include",
        headers:{"Content-Type":"application/json"},
        body:JSON.stringify({ messages: history, systemPrompt, licenseKey }),
      });
      const data = await res.json();
      const reply = data.content || data.error || "Sorry, no response.";
      setMsgs(m=>[...m,{role:"assistant",content:reply}]);
    } catch { setMsgs(m=>[...m,{role:"assistant",content:"Error connecting to AI. Check your connection."}]); }
    setLoading(false);
  };

  const suggestions = ["Why is my error rate this high?","What does this register value mean?","How do I reduce jitter?","Any issues with these settings?"];

  return (
    <div style={{marginTop:8}}>
      <button onClick={()=>setOpen(o=>!o)}
        style={{width:"100%",padding:"10px 14px",background:open?T.accent+"12":T.surface,border:`1px solid ${open?T.accent+"44":T.border}`,borderRadius:8,color:open?T.accent:T.textMid,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontFamily:T.sans,fontSize:13,fontWeight:500,transition:"all 0.2s"}}>
        <span>🤖</span><span>AI Engineer Assistant</span>
        <span style={{marginLeft:"auto",fontSize:10,background:`linear-gradient(135deg,${T.gold},#ef4444)`,borderRadius:3,padding:"1px 6px",color:"#fff",fontWeight:700}}>PRO</span>
        <span style={{fontSize:11,opacity:.5}}>{open?"▲":"▼"}</span>
      </button>
      {open && (
        <div style={{border:`1px solid ${T.border}`,borderTop:"none",borderRadius:"0 0 8px 8px",background:T.surface,overflow:"hidden"}}>
          <div style={{height:240,overflowY:"auto",padding:"12px 14px",display:"flex",flexDirection:"column",gap:10}}>
            {msgs.length===0 && (
              <div style={{display:"flex",flexDirection:"column",gap:8,marginTop:8}}>
                <p style={{color:T.textMuted,fontSize:12,fontFamily:T.sans,textAlign:"center"}}>Ask anything about your calculations.</p>
                <div style={{display:"flex",flexWrap:"wrap",gap:6,justifyContent:"center"}}>
                  {suggestions.map(s=>(
                    <button key={s} onClick={()=>{ setInput(s); }}
                      style={{padding:"4px 10px",background:T.card,border:`1px solid ${T.border}`,borderRadius:100,color:T.textMid,cursor:"pointer",fontSize:11,fontFamily:T.sans,transition:"border-color .15s"}}
                      onMouseEnter={e=>e.currentTarget.style.borderColor=T.accent+"44"}
                      onMouseLeave={e=>e.currentTarget.style.borderColor=T.border}>
                      {s}
                    </button>
                  ))}
                </div>
              </div>
            )}
            {msgs.map((m,i)=>(
              <div key={i} style={{display:"flex",justifyContent:m.role==="user"?"flex-end":"flex-start"}}>
                <div style={{maxWidth:"85%",padding:"8px 12px",borderRadius:m.role==="user"?"12px 12px 3px 12px":"12px 12px 12px 3px",background:m.role==="user"?T.accent+"22":T.card,border:`1px solid ${m.role==="user"?T.accent+"33":T.border}`,fontSize:12,color:T.text,fontFamily:T.sans,lineHeight:1.65,whiteSpace:"pre-wrap"}}>
                  {m.content}
                </div>
              </div>
            ))}
            {loading && (
              <div style={{display:"flex",alignItems:"center",gap:6}}>
                <div style={{display:"flex",gap:3}}>{[0,1,2].map(i=><div key={i} style={{width:5,height:5,borderRadius:"50%",background:T.accent,opacity:.6,animation:`pulse 1s ${i*.2}s infinite`}}/>)}</div>
                <span style={{fontSize:11,color:T.textMuted}}>Thinking…</span>
              </div>
            )}
            <div ref={bottomRef}/>
          </div>
          <div style={{display:"flex",borderTop:`1px solid ${T.border}`}}>
            <input value={input} onChange={e=>setInput(e.target.value)} onKeyDown={e=>e.key==="Enter"&&send()}
              placeholder="e.g. Why is my baud error >2%?"
              style={{flex:1,background:"transparent",border:"none",outline:"none",padding:"10px 14px",fontSize:12,color:T.text,fontFamily:T.sans}}/>
            <button onClick={send} disabled={loading||!input.trim()}
              style={{padding:"10px 16px",background:input.trim()?T.accent:"transparent",border:"none",color:input.trim()?"#fff":T.textMuted,cursor:input.trim()?"pointer":"default",fontSize:12,fontFamily:T.sans,fontWeight:600,transition:"all .15s"}}>
              Send
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── CLOCK TREE ───────────────────────────────────────────────────────────────
function ClockTree({ profile, sysclk, pllVco, hseHz }) {
  const boxes = [
    {id:"hse",label:"HSE",    value:fmtHz(hseHz),   x:20,  y:80,  color:T.accent3, w:100},
    {id:"hsi",label:"HSI",    value:"16 MHz",        x:20,  y:160, color:T.textMuted,w:100},
    {id:"pll",label:"PLL VCO",value:fmtHz(pllVco),  x:165, y:110, color:T.accent2, w:110},
    {id:"sys",label:"SYSCLK", value:fmtHz(sysclk),  x:325, y:90,  color:T.accent,  w:120},
    {id:"ahb",label:"AHB Bus",value:fmtHz(sysclk),  x:495, y:50,  color:T.accent,  w:110},
    {id:"ap1",label:"APB1 (÷4)",value:fmtHz(sysclk/4),x:495,y:130,color:T.warn,    w:110},
    {id:"ap2",label:"APB2 (÷2)",value:fmtHz(sysclk/2),x:495,y:205,color:T.warn,    w:110},
  ];
  const lines=[
    {x1:120,y1:100,x2:165,y2:130},{x1:120,y1:180,x2:165,y2:145},
    {x1:275,y1:130,x2:325,y2:115},{x1:445,y1:115,x2:495,y2:70},
    {x1:445,y1:115,x2:495,y2:150},{x1:445,y1:115,x2:495,y2:225},
  ];
  return (
    <div style={{overflowX:"auto",background:T.input,borderRadius:8,border:`1px solid ${T.border}`,padding:"8px"}}>
      <svg width="640" height="270" style={{display:"block",minWidth:640}}>
        {[...Array(13)].map((_,i)=><line key={i} x1={i*50} y1={0} x2={i*50} y2={270} stroke={T.border} strokeWidth="0.5" opacity="0.4"/>)}
        {lines.map((l,i)=><line key={i} x1={l.x1} y1={l.y1} x2={l.x2} y2={l.y2} stroke={T.borderLight} strokeWidth="1.5" strokeDasharray="4,3"/>)}
        {boxes.map(b=>(
          <g key={b.id}>
            <rect x={b.x} y={b.y-22} width={b.w} height={44} rx={6} fill={b.color+"15"} stroke={b.color+"55"} strokeWidth="1.5"/>
            <text x={b.x+b.w/2} y={b.y-6} textAnchor="middle" fill={b.color} fontSize="9" fontFamily={T.sans} fontWeight="700" letterSpacing="0.08em">{b.label}</text>
            <text x={b.x+b.w/2} y={b.y+10} textAnchor="middle" fill={T.text} fontSize="11" fontFamily={T.mono}>{b.value}</text>
          </g>
        ))}
        <text x={320} y={260} textAnchor="middle" fill={T.textMuted} fontSize="10" fontFamily={T.sans}>{profile.name} Clock Tree Diagram</text>
      </svg>
    </div>
  );
}

// ─── PRO API (server-enforced; no client-side unlock) ─────────────────────────
const proFetch = (url, body) =>
  fetch(url, {
    method: "POST",
    credentials: "include",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  }).then((r) => r.json());

async function establishProSession(licenseKey) {
  const key = String(licenseKey || "").trim().toUpperCase();
  if (!isValidLicenseKeyFormat(key)) throw new Error("Invalid license key format");
  const sess = await proFetch("/api/pro-session", { licenseKey: key });
  if (!sess.valid) {
    throw new Error(sess.error || "Could not start PRO session. Use https://regcalc.vercel.app/app and try again.");
  }
  const status = await proFetch("/api/pro-status", { licenseKey: key });
  if (!status.pro) {
    throw new Error(status.error || "PRO session expired. Enter your license key again.");
  }
  localStorage.setItem("regcalc_pro_key", key);
  return { key, plan: status.plan };
}

function ProHalExport({ proKey, proActive, onUpgrade, calculator, profileKey, inputs, title }) {
  const [code, setCode] = useState("");
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState("");
  const inputsKey = JSON.stringify(inputs);

  useEffect(() => {
    if (!proActive || !proKey) return;
    let cancelled = false;
    setLoading(true);
    setErr("");
    proFetch("/api/pro-export", { licenseKey: proKey, calculator, profileKey, inputs })
      .then((d) => {
        if (cancelled) return;
        if (d.code) setCode(d.code);
        else setErr(d.error || "Export unavailable");
      })
      .catch(() => { if (!cancelled) setErr("Could not load export."); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [proActive, proKey, calculator, profileKey, inputsKey]);

  if (!proActive || !proKey) return <ProGate onUpgrade={onUpgrade} />;
  if (loading) return <p style={{color:T.textMuted,fontSize:12,fontFamily:T.sans,marginTop:14}}>Loading HAL export…</p>;
  if (err) return <p style={{color:T.danger,fontSize:12,fontFamily:T.sans,marginTop:14}}>{err}</p>;
  return <CodeBlock code={code} title={title} />;
}

function ProClockTreePanel({ proKey, proActive, onUpgrade, profile, profileKey, inputs }) {
  const [show, setShow] = useState(false);
  const [tree, setTree] = useState(null);
  const [err, setErr] = useState("");
  const inputsKey = JSON.stringify(inputs);

  const load = () => {
    if (!proKey || !proActive) return;
    setErr("");
    proFetch("/api/pro-export", {
      licenseKey: proKey,
      calculator: "pll",
      profileKey,
      inputs,
      feature: "clockTree",
    }).then((d) => {
      if (d.clockTree) setTree(d.clockTree);
      else setErr(d.error || "Clock tree unavailable");
    }).catch(() => setErr("Could not load clock tree."));
  };

  useEffect(() => {
    if (show && proActive && proKey && !tree) load();
  }, [show, proActive, proKey, inputsKey]);

  if (!proActive || !proKey) return null;

  return (
    <>
      <button onClick={() => { setShow((s) => !s); if (!show) load(); }}
        style={{padding:"8px 14px",background:show?T.accent2+"18":T.surface,border:`1px solid ${show?T.accent2+"55":T.border}`,borderRadius:7,color:show?T.accent2:T.textMid,cursor:"pointer",fontSize:12,fontFamily:T.sans,textAlign:"left",width:"100%",marginTop:8}}>
        {show ? "▲ Hide Clock Tree Diagram" : "▼ Show Clock Tree Diagram"}
      </button>
      {show && tree && (
        <ClockTree profile={{...profile, name: tree.profileName}} sysclk={tree.sysclk} pllVco={tree.pllVco} hseHz={tree.hseHz}/>
      )}
      {show && err && <p style={{color:T.danger,fontSize:11,fontFamily:T.sans,marginTop:8}}>{err}</p>}
    </>
  );
}

// ─── PRO GATE ─────────────────────────────────────────────────────────────────
function ProGate({ onUpgrade }) {
  return (
    <div style={{marginTop:14,background:`linear-gradient(135deg,${T.accent2}12,${T.accent}08)`,border:`1px dashed ${T.accent2}44`,borderRadius:10,padding:"18px 20px",textAlign:"center"}}>
      <div style={{width:40,height:40,background:`linear-gradient(135deg,${T.gold}22,${T.accent2}22)`,border:`1px solid ${T.gold}33`,borderRadius:10,display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px",fontSize:20}}>🔒</div>
      <p style={{color:T.text,fontWeight:700,fontSize:14,margin:"0 0 4px",fontFamily:T.sans}}>PRO Feature</p>
      <p style={{color:T.textMuted,fontSize:12,margin:"0 0 16px",fontFamily:T.sans}}>HAL/LL code export, AI assistant & clock tree diagrams</p>
      <button onClick={onUpgrade} style={{padding:"9px 26px",background:`linear-gradient(135deg,${T.gold},#ef4444)`,border:"none",borderRadius:7,color:"#fff",cursor:"pointer",fontSize:13,fontWeight:700,fontFamily:T.sans,letterSpacing:"0.02em",boxShadow:`0 4px 16px ${T.gold}33`}}>
        Upgrade to PRO →
      </button>
    </div>
  );
}

// ─── PRICING MODAL ────────────────────────────────────────────────────────────
function PricingModal({ onClose, onSuccess }) {
  const [plan,     setPlan]     = useState("yearly");
  const [step,     setStep]     = useState("plans");
  const [email,    setEmail]    = useState("");
  const [emailErr, setEmailErr] = useState("");
  const [licKey,   setLicKey]   = useState("");
  const [licErr,   setLicErr]   = useState("");
  const [proc,     setProc]     = useState(false);
  const [genKey,   setGenKey]   = useState("");

  const plans = {
    monthly:  { price:"$7",   period:"/mo",  label:"Monthly",  badge:null,          saves:null },
    yearly:   { price:"$49",  period:"/yr",  label:"Yearly",   badge:"BEST VALUE",  saves:"Save $35" },
    lifetime: { price:"$129", period:" once",label:"Lifetime", badge:"ONE-TIME",    saves:"Forever" },
  };

  const validEmail = v => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
  const formOk     = validEmail(email);

  const LS_URLS = {
    monthly:  "https://regcalc.lemonsqueezy.com/checkout/buy/04d6ed83-d29a-43c1-87fb-6dd44e07882c",
    yearly:   "https://regcalc.lemonsqueezy.com/checkout/buy/8abbe2d1-007e-4eb6-97bf-637b4f2136cf",
    lifetime: "https://regcalc.lemonsqueezy.com/checkout/buy/cb12e337-cbae-4a2d-874d-1db8f4d85be7",
  };

  const handlePurchase = () => {
    if (!validEmail(email)) { setEmailErr("Please enter a valid email."); return; }
    if (!formOk || proc) return;
    setProc(true);
    const base = LS_URLS[plan];
    const url = `${base}?checkout[email]=${encodeURIComponent(email)}`;
    window.open(url, "_blank");
    setTimeout(() => setProc(false), 2000);
  };

  const handleLicense = async () => {
    const key = licKey.trim().toUpperCase();
    if (!key) return;
    if (!isValidLicenseKeyFormat(key)) {
      setLicErr("Invalid format. Use letters, numbers, and dashes only (e.g. REGCALC-BETA-2026).");
      return;
    }
    setLicErr("");
    setProc(true);
    try {
      const res = await fetch("/api/validate-license", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ licenseKey: key }),
      });
      let data;
      try {
        data = await res.json();
      } catch {
        setLicErr("Server returned an invalid response. Try again in a moment.");
        return;
      }
      if (!data.valid) {
        setLicErr(data.error || "Invalid or expired license key.");
        return;
      }
      try {
        await establishProSession(key);
        localStorage.setItem("regcalc_pro_key", key);
        setGenKey(key);
        onSuccess(key);
        setStep("success");
      } catch (sessionErr) {
        setLicErr(sessionErr.message || "License is valid but PRO session failed. Refresh the page and try again.");
      }
    } catch (e) {
      setLicErr("Could not connect to validation service. Check your connection and try again.");
    } finally {
      setProc(false);
    }
  };

  const s = {
    input: {background:T.input,border:`1px solid ${T.inputBorder}`,borderRadius:7,color:T.text,padding:"10px 12px",fontSize:13,outline:"none",fontFamily:T.sans,width:"100%",transition:"border-color .15s"},
  };

  return (
    <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,.82)",backdropFilter:"blur(12px)",zIndex:200,display:"flex",alignItems:"center",justifyContent:"center",padding:16}} onClick={e=>e.target===e.currentTarget&&onClose()}>
      <div style={{background:T.surface,border:`1px solid ${T.borderLight}`,borderRadius:16,width:"100%",maxWidth:480,maxHeight:"92vh",overflowY:"auto",boxShadow:`0 40px 80px rgba(0,0,0,.6),0 0 0 1px rgba(255,255,255,.04)`}}>
        <div className="modal-header" style={{padding:"20px 24px 0",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
          <div>
            <h2 style={{fontSize:18,fontWeight:800,fontFamily:T.sans,color:T.text,letterSpacing:"-0.03em"}}>Unlock RegCalc PRO</h2>
            <p style={{fontSize:12,color:T.textMuted,fontFamily:T.sans,marginTop:2}}>HAL code export · AI assistant · Clock tree diagrams</p>
          </div>
          <button onClick={onClose} style={{background:"none",border:"none",color:T.textMuted,cursor:"pointer",fontSize:22,lineHeight:1,padding:"0 4px"}}>×</button>
        </div>

        {/* Step tabs */}
        <div style={{display:"flex",margin:"16px 0 0",padding:"0 24px"}}>
          {["plans","checkout","license"].map((s2,i)=>(
            <button key={s2} onClick={()=>{ if(s2==="plans"||step!=="plans") setStep(s2); }}
              style={{flex:1,padding:"8px",background:"transparent",border:"none",borderBottom:`2px solid ${step===s2?T.accent:T.border}`,color:step===s2?T.accent:(s2!=="plans"&&step==="plans"?T.textMuted+"55":T.textMuted),cursor:(s2!=="plans"&&step==="plans")?"default":"pointer",fontSize:11,fontFamily:T.sans,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",transition:"all .2s"}}>
              {s2==="plans"?"1. Plans":s2==="checkout"?"2. Checkout":"3. License"}
            </button>
          ))}
        </div>

        <div className="modal-body" style={{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:14}}>

          {/* PLANS */}
          {step==="plans" && (<>
            <div className="plan-btns" style={{display:"flex",gap:8,flexWrap:"wrap"}}>
              {Object.entries(plans).map(([k,v])=>(
                <button key={k} onClick={()=>setPlan(k)}
                  style={{flex:1,minWidth:90,padding:"12px 10px",background:plan===k?T.goldGlow:"transparent",border:`1px solid ${plan===k?T.gold+"66":T.border}`,borderRadius:10,color:plan===k?T.gold:T.textMid,cursor:"pointer",fontFamily:T.sans,textAlign:"center",transition:"all .15s",position:"relative"}}>
                  {v.badge && <div style={{position:"absolute",top:-9,left:"50%",transform:"translateX(-50%)",background:`linear-gradient(135deg,${T.gold},#ef4444)`,borderRadius:100,padding:"2px 8px",fontSize:8,fontWeight:700,color:"#fff",whiteSpace:"nowrap",letterSpacing:".05em",fontFamily:T.mono}}>{v.badge}</div>}
                  <div style={{fontSize:20,fontWeight:800,fontFamily:T.sans,letterSpacing:"-0.04em"}}>{v.price}</div>
                  <div style={{fontSize:10,color:T.textMuted,marginTop:1}}>{v.period}</div>
                  <div style={{fontSize:11,fontWeight:600,marginTop:4}}>{v.label}</div>
                  {v.saves && <div style={{fontSize:10,color:T.accent3,marginTop:2}}>{v.saves}</div>}
                </button>
              ))}
            </div>

            <div style={{display:"flex",flexDirection:"column",gap:7,background:T.card,borderRadius:9,padding:"14px 16px",border:`1px solid ${T.border}`}}>
              {[["All 6 calculators","✓"],["Real-time calculations","✓"],["HAL & LL code export","✓"],["AI engineer assistant","✓"],["PLL clock tree diagrams","✓"],["All future MCU profiles","✓"],["Priority support","✓"]].map(([f,v])=>(
                <div key={f} style={{display:"flex",justifyContent:"space-between",fontSize:12,color:T.textMid,fontFamily:T.sans}}>
                  <span>{f}</span><span style={{color:T.accent3,fontWeight:700}}>{v}</span>
                </div>
              ))}
            </div>

            <button onClick={()=>setStep("checkout")} style={{padding:"13px",background:`linear-gradient(135deg,${T.gold},#ef4444)`,border:"none",borderRadius:10,color:"#fff",cursor:"pointer",fontSize:14,fontWeight:700,fontFamily:T.sans,boxShadow:`0 4px 18px ${T.gold}33`}}>
              Continue with {plans[plan].label} — {plans[plan].price}{plans[plan].period} →
            </button>
            <p style={{textAlign:"center",fontSize:11,color:T.textMuted,fontFamily:T.sans}}>🔒 Secure checkout · 30-day refund guarantee · Instant delivery</p>
            <div style={{borderTop:`1px solid ${T.border}`,paddingTop:12,textAlign:"center"}}>
              <p style={{fontSize:12,color:T.textMuted,fontFamily:T.sans,marginBottom:8}}>Already purchased? Enter your license key:</p>
              <button onClick={()=>setStep("license")} style={{background:"transparent",border:`1px solid ${T.border}`,borderRadius:7,padding:"7px 18px",color:T.textMid,cursor:"pointer",fontSize:12,fontFamily:T.sans}}>Enter License Key</button>
            </div>
          </>)}

          {/* CHECKOUT */}
          {step==="checkout" && (<>
            <div style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:8,padding:"12px 16px",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <div>
                <p style={{fontSize:13,fontWeight:600,color:T.text,fontFamily:T.sans,margin:0}}>RegCalc PRO — {plans[plan].label}</p>
                <p style={{fontSize:11,color:T.textMuted,fontFamily:T.sans,margin:0}}>Billed {plan==="lifetime"?"once":plan}</p>
              </div>
              <span style={{fontFamily:T.mono,fontWeight:700,color:T.gold,fontSize:16}}>{plans[plan].price}</span>
            </div>
            <div style={{display:"flex",flexDirection:"column",gap:10}}>
              <div>
                <label style={{fontSize:11,color:T.textMuted,fontFamily:T.sans,display:"block",marginBottom:5}}>Email address</label>
                <input value={email} onChange={e=>{setEmail(e.target.value);setEmailErr("");}} onBlur={()=>email&&!validEmail(email)&&setEmailErr("Please enter a valid email.")} placeholder="you@example.com" type="email" style={{...s.input,borderColor:emailErr?T.danger+"66":T.inputBorder}}/>
                {emailErr && <p style={{fontSize:11,color:T.danger,fontFamily:T.sans,marginTop:4}}>{emailErr}</p>}
              </div>
              <div>
                <p style={{fontSize:11,color:T.textMuted,fontFamily:T.sans,lineHeight:1.5,margin:0}}>Payment is completed securely on Lemon Squeezy. Your license key will be emailed instantly.</p>
              </div>
            </div>
            <button onClick={handlePurchase} disabled={proc||!formOk}
              style={{padding:"13px",background:(!proc&&formOk)?`linear-gradient(135deg,${T.gold},#ef4444)`:T.border,border:"none",borderRadius:10,color:(!proc&&formOk)?"#fff":T.textMuted,cursor:(!proc&&formOk)?"pointer":"default",fontSize:14,fontWeight:700,fontFamily:T.sans,transition:"all .2s"}}>
              {proc ? "Opening checkout..." : `Continue to Checkout — ${plans[plan].price}`}
            </button>
            <p style={{textAlign:"center",fontSize:10,color:T.textMuted,fontFamily:T.sans}}>🔒 Secure checkout · 30-day refund guarantee</p>
          </>)}

          {/* LICENSE */}
          {step==="license" && (<>
            <div style={{background:T.card,border:`1px solid ${T.border}`,borderRadius:8,padding:"16px",textAlign:"center"}}>
              <div style={{fontSize:32,marginBottom:8}}>🔑</div>
              <p style={{color:T.text,fontWeight:600,fontSize:14,fontFamily:T.sans,margin:"0 0 4px"}}>Activate Your License</p>
              <p style={{color:T.textMuted,fontSize:12,fontFamily:T.sans,margin:0}}>Purchase email, or beta key below while we are in testing.</p>
            </div>
            <div style={{background:T.accentGlow,border:`1px solid ${T.accent}33`,borderRadius:8,padding:"10px 12px",fontSize:11,fontFamily:T.sans,color:T.textMid,lineHeight:1.5}}>
              <strong style={{color:T.accent}}>Public beta:</strong> use{" "}
              <code style={{fontFamily:T.mono,color:T.accent3}}>{BETA_LICENSE_PUBLIC}</code>
              {" "}for free PRO during testing (no payment required).
            </div>
            <div>
              <label style={{fontSize:11,color:T.textMuted,fontFamily:T.sans,display:"block",marginBottom:5}}>License Key</label>
              <input value={licKey} onChange={e=>{setLicKey(e.target.value);setLicErr("");}} placeholder={BETA_LICENSE_PUBLIC}
                style={{...s.input,fontFamily:T.mono,letterSpacing:"0.05em",borderColor:licErr?T.danger+"66":T.inputBorder}}/>
              {licErr && <p style={{fontSize:11,color:T.danger,fontFamily:T.sans,marginTop:5}}>{licErr}</p>}
            </div>
            <button onClick={handleLicense} disabled={proc||!licKey.trim()}
              style={{padding:"12px",background:(!proc&&licKey.trim())?`linear-gradient(135deg,${T.accent2},${T.accent})`:T.border,border:"none",borderRadius:9,color:(!proc&&licKey.trim())?"#fff":T.textMuted,cursor:(!proc&&licKey.trim())?"pointer":"default",fontSize:14,fontWeight:700,fontFamily:T.sans}}>
              {proc ? "Validating..." : "Activate License"}
            </button>
            <p style={{textAlign:"center",fontSize:11,color:T.textMuted,fontFamily:T.sans}}>License keys are delivered by email after purchase.</p>
          </>)}

          {/* SUCCESS */}
          {step==="success" && (
            <div style={{textAlign:"center",padding:"20px 0"}}>
              <div style={{fontSize:52,marginBottom:14}}>🎉</div>
              <h3 style={{color:T.text,fontFamily:T.sans,fontSize:20,fontWeight:700,margin:"0 0 8px"}}>PRO Activated!</h3>
              <p style={{color:T.textMuted,fontSize:13,fontFamily:T.sans,margin:"0 0 20px"}}>Welcome to RegCalc PRO. All features are now unlocked.</p>
              {genKey && (
                <div style={{background:T.card,border:`1px solid ${T.accent3}44`,borderRadius:8,padding:"12px 16px",marginBottom:20}}>
                  <p style={{fontSize:10,color:T.textMuted,fontFamily:T.sans,margin:"0 0 6px",textTransform:"uppercase",letterSpacing:"0.1em"}}>Your License Key (save this)</p>
                  <code style={{fontSize:14,fontFamily:T.mono,color:T.accent3}}>{genKey}</code>
                </div>
              )}
              <button onClick={()=>{onSuccess(genKey);onClose();}}
                style={{padding:"12px 32px",background:`linear-gradient(135deg,${T.accent3},${T.accent})`,border:"none",borderRadius:9,color:"#fff",cursor:"pointer",fontSize:14,fontWeight:700,fontFamily:T.sans}}>
                Start Using PRO →
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── EXIT INTENT MODAL ────────────────────────────────────────────────────────
function ExitModal({ onClose, onUpgrade }) {
  return (
    <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,.85)",backdropFilter:"blur(14px)",zIndex:250,display:"flex",alignItems:"center",justifyContent:"center",padding:16}}>
      <div style={{background:T.surface,border:`1px solid ${T.gold}44`,borderRadius:18,padding:"32px 28px",width:"100%",maxWidth:400,textAlign:"center",boxShadow:`0 0 60px ${T.gold}15`}}>
        <div style={{fontSize:40,marginBottom:12}}>⚡</div>
        <h3 style={{fontSize:20,fontWeight:800,fontFamily:T.sans,color:T.text,marginBottom:8,letterSpacing:"-0.03em"}}>Wait — before you go</h3>
        <p style={{fontSize:14,color:T.textMid,fontFamily:T.sans,lineHeight:1.6,marginBottom:6}}>Get <strong style={{color:T.gold}}>20% off PRO</strong> for the next 10 minutes.</p>
        <p style={{fontSize:12,color:T.textMuted,fontFamily:T.sans,marginBottom:24}}>HAL code export, AI assistant & clock tree diagrams — use code <code style={{fontFamily:T.mono,color:T.accent,background:T.accentGlow,padding:"1px 6px",borderRadius:4}}>EXIT20</code></p>
        <div style={{display:"flex",flexDirection:"column",gap:8}}>
          <button onClick={onUpgrade} style={{padding:"13px",background:`linear-gradient(135deg,${T.gold},#ef4444)`,border:"none",borderRadius:10,color:"#fff",cursor:"pointer",fontSize:14,fontWeight:700,fontFamily:T.sans,boxShadow:`0 4px 18px ${T.gold}33`}}>
            Claim 20% Off PRO →
          </button>
          <button onClick={onClose} style={{padding:"10px",background:"transparent",border:`1px solid ${T.border}`,borderRadius:10,color:T.textMuted,cursor:"pointer",fontSize:13,fontFamily:T.sans}}>
            No thanks, continue for free
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── CALCULATORS ──────────────────────────────────────────────────────────────
function ProfileSdkNote({ profile }) {
  if (!profile?.codeSdk) return null;
  return (
    <div style={{background:T.accent+"0c",border:`1px solid ${T.accent}33`,borderRadius:8,padding:"8px 12px",fontSize:11,color:T.textMid,fontFamily:T.sans}}>
      <strong style={{color:T.accent}}>{profile.name}</strong> — calculations use {profile.codeSdk} formulas. Adjust clock fields if your board differs.
    </div>
  );
}

function BetaBanner() {
  return (
    <div style={{background:`linear-gradient(90deg,${T.accent2}14,${T.gold}10)`,border:`1px solid ${T.accent}33`,borderRadius:10,padding:"12px 16px",marginBottom:14,fontSize:12,fontFamily:T.sans,color:T.textMid,lineHeight:1.55}}>
      <strong style={{color:T.accent}}>Public beta</strong> — RegCalc is in active testing. Payments (Lemon Squeezy) are pending approval; checkout may be test-only for now.
      <span style={{display:"block",marginTop:6}}>
        <strong style={{color:T.gold}}>Beta testers:</strong> unlock PRO free with license key{" "}
        <code style={{fontFamily:T.mono,color:T.accent3,background:T.card,padding:"2px 8px",borderRadius:4}}>{BETA_LICENSE_PUBLIC}</code>
        {" "}(Get PRO → Enter License Key). Each MCU uses its native SDK math (HAL, ESP-IDF, Pico SDK, nRF SDK, avr-libc).
      </span>
    </div>
  );
}

function BaudCalc({ profile, profileKey, proActive, proKey, onUpgrade, onCalc, restoreSnap, onRestored }) {
  const defaultClk = String(profile.uartClkMHz ?? profile.maxClock);
  const [clk, setClk] = useState(defaultClk);
  const [baud, setBaud] = useState("115200");
  const [os, setOs] = useState(profile.uartModel === "avr" ? "16" : "16");
  useRestoreInputs(restoreSnap, "baud", (inp) => {
    if (inp.clk != null) setClk(String(inp.clk));
    if (inp.baud != null) setBaud(String(inp.baud));
    if (inp.os != null) setOs(String(inp.os));
  }, onRestored);
  const eng = getEngine();
  const r = eng ? eng.calcUart(profile, { clk, baud, os }) : { reg: "—", actual: 0, err: 0, regLabel: "—", bitPeriod: 0 };
  const baudN = parseFloat(baud);
  const ctx = { calculator: "UART/Baud", clkMHz: parseFloat(clk), baud: baudN, reg: r.reg, error: (r.err || 0).toFixed(3) + "%" };
  const summary = `${profile.name} ${clk}MHz → ${r.regLabel}=${r.reg} err=${(r.err || 0).toFixed(2)}%`;
  useEffect(() => { onCalc({ tab: "baud", mcuKey: profileKey, mcu: profile.name, summary, ctx, inputs: { clk, baud, os }, time: ts() }); }, [clk, baud, os, profileKey, profile.name]);
  const shareUrl = encodeShare("baud", profile.name, { pclk: clk, baud, os });
  const osOptions = profile.uartModel === "avr"
    ? [{ v: "16", l: "Normal (÷16)" }, { v: "8", l: "Double speed (÷8, U2X)" }]
    : profile.uartModel === "stm32"
      ? [{ v: "16", l: "16× Standard" }, { v: "8", l: "8× High Speed" }]
      : [{ v: "16", l: "Default" }];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
      <ProfileSdkNote profile={profile} />
      <div className="calc-grid-2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <Field label="UART Clock" value={clk} onChange={setClk} unit="MHz" hint={`Default ${profile.uartClkMHz} MHz · max ${(profile.uartMaxBaud / 1e6).toFixed(1)} Mbps`} />
        {(profile.uartModel === "stm32" || profile.uartModel === "avr") && (
          <Sel label={profile.uartModel === "avr" ? "Speed mode" : "Oversampling"} value={os} onChange={setOs} options={osOptions} />
        )}
        <Field label="Target Baud Rate" value={baud} onChange={setBaud} unit="bps" />
      </div>
      <Divider />
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        <Res label={r.regLabel} value={isFinite(r.reg) ? r.reg : "—"} highlight copy />
        {r.reg2 != null && <Res label={profile.uartModel === "rp2040" ? "Fractional (÷64)" : "Fractional (÷16)"} value={r.reg2} />}
        {r.extra?.register && <Res label="Register value" value={r.extra.register} highlight copy />}
        <Res label="Actual Baud Rate" value={isFinite(r.actual) ? r.actual.toFixed(0) + " bps" : "—"} />
        <Res label="Error" value={isFinite(r.err) ? r.err.toFixed(4) + " %" : "—"} color={Math.abs(r.err) > 2 ? T.danger : undefined} />
        <Res label="Bit Period" value={fmtTime(r.bitPeriod || 1 / baudN)} />
      </div>
      {Math.abs(r.err) > 2 && isFinite(r.err) && <Warn msg="Error >2% — try a different UART clock or baud." />}
      <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 4 }}>
        <ShareBtn url={shareUrl} />
      </div>
      {proActive && proKey ? (
        <>
          <ProHalExport proKey={proKey} proActive={proActive} onUpgrade={onUpgrade} calculator="uart" profileKey={profileKey} inputs={{ clk, baud, os }} title={sdkExportTitle(profile, "uart_init.c")} />
          <AIAssistant context={ctx} licenseKey={proKey} />
        </>
      ) : <ProGate onUpgrade={onUpgrade} />}
    </div>
  );
}

function TimerCalc({ profile, profileKey, proActive, proKey, onUpgrade, onCalc, restoreSnap, onRestored }) {
  const [clk, setClk] = useState(String(profile.timerClkMHz ?? profile.maxClock));
  const [target, setTarget] = useState("1000");
  const [tUnit, setTUnit] = useState("1");
  const [mode, setMode] = useState("auto");
  const [psc, setPsc] = useState("71");
  const [arr, setArr] = useState("999");
  useRestoreInputs(restoreSnap, "timer", (inp) => {
    if (inp.clk != null) setClk(String(inp.clk));
    if (inp.target != null) setTarget(String(inp.target));
    if (inp.tUnit != null) setTUnit(String(inp.tUnit));
    if (inp.mode != null) setMode(String(inp.mode));
    if (inp.psc != null) setPsc(String(inp.psc));
    if (inp.arr != null) setArr(String(inp.arr));
  }, onRestored);
  const eng = getEngine();
  const tr = eng ? eng.calcTimer(profile, { clk, target, tUnit, mode, psc, arr }) : { psc: 0, arr: 0, freq: 0, timerClk: 0, resolution: 0, pscLabel: "PSC", arrLabel: "ARR" };
  const targetHz = parseFloat(target) * parseFloat(tUnit);
  const ctx = { calculator: "Timer", clkMHz: parseFloat(clk), targetHz, psc: tr.psc, arr: tr.arr, freq: fmtHz(tr.freq) };
  const summary = `${profile.name} ${clk}MHz → ${tr.pscLabel}=${tr.psc} ${tr.arrLabel}=${tr.arr} → ${fmtHz(tr.freq)}`;
  useEffect(() => { onCalc({ tab: "timer", mcuKey: profileKey, mcu: profile.name, summary, ctx, inputs: { clk, target, tUnit, mode, psc, arr }, time: ts() }); }, [clk, target, tUnit, psc, arr, mode, profileKey, profile.name]);
  return (
    <div style={{display:"flex",flexDirection:"column",gap:11}}>
      <ProfileSdkNote profile={profile}/>
      <div className="tab-mode-row" style={{display:"flex",gap:6,marginBottom:2}}>
        {["auto","manual"].map(m=><button key={m} onClick={()=>setMode(m)} style={{padding:"5px 16px",borderRadius:6,border:`1px solid ${mode===m?T.accent:T.border}`,background:mode===m?T.accent+"18":"transparent",color:mode===m?T.accent:T.textMuted,cursor:"pointer",fontSize:12,fontFamily:T.sans}}>{m==="auto"?"Auto (from frequency)":"Manual PSC/ARR"}</button>)}
      </div>
      <div className="calc-grid-2" style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
        <Field label="Timer Clock" value={clk} onChange={setClk} unit="MHz" hint={`Default ${profile.timerClkMHz} MHz${profile.family === "stm32" ? " (×2 APB on F4/H7)" : ""}`}/>
        {mode==="auto"?<><Sel label="Target Unit" value={tUnit} onChange={setTUnit} options={[{v:"1000000",l:"MHz"},{v:"1000",l:"kHz"},{v:"1",l:"Hz"}]}/><Field label="Target Frequency" value={target} onChange={setTarget}/></>:<><Field label={tr.pscLabel} value={psc} onChange={setPsc} hint="prescaler"/><Field label={tr.arrLabel} value={arr} onChange={setArr} hint="period"/></>}
      </div>
      <Divider/>
      <div style={{display:"flex",flexDirection:"column",gap:6}}>
        <Res label={tr.pscLabel} value={isFinite(tr.psc)?tr.psc:"—"} highlight copy/>
        <Res label={tr.arrLabel} value={isFinite(tr.arr)?tr.arr:"—"} highlight copy/>
        <Res label="Timer Clock" value={fmtHz(tr.timerClk)}/>
        <Res label="Output Frequency" value={fmtHz(tr.freq)}/>
        <Res label="Period" value={fmtTime(tr.period || 1/tr.freq)}/>
        <Res label="Resolution" value={isFinite(tr.resolution)?tr.resolution.toFixed(2)+" bits":"—"}/>
      </div>
      {proActive && proKey ? (
        <>
          <ProHalExport proKey={proKey} proActive={proActive} onUpgrade={onUpgrade} calculator="timer" profileKey={profileKey} inputs={{ clk, target, tUnit, mode, psc, arr }} title={sdkExportTitle(profile, "timer_init.c")}/>
          <AIAssistant context={ctx} licenseKey={proKey}/>
        </>
      ) : <ProGate onUpgrade={onUpgrade}/>}
    </div>
  );
}

function PLLCalc({ profile, profileKey, proActive, proKey, onUpgrade, onCalc, restoreSnap, onRestored }) {
  const [hse,setHse]=useState(String(profile.hse));
  const [m,setM]=useState(String(profile.pllM));
  const [n,setN]=useState(String(profile.pllN));
  const [p,setP]=useState(String(profile.pllP));
  const [q,setQ]=useState(String(profile.pllQ));
  useRestoreInputs(restoreSnap, "pll", (inp) => {
    if (inp.hse != null) setHse(String(inp.hse));
    if (inp.m != null) setM(String(inp.m));
    if (inp.n != null) setN(String(inp.n));
    if (inp.p != null) setP(String(inp.p));
    if (inp.q != null) setQ(String(inp.q));
  }, onRestored);
  const eng = getEngine();
  const pl = eng ? eng.calcPll(profile, { hse, m, n, p, q }) : { sysclk: 0, vcoIn: 0, vcoOut: 0, usbClk: 0, warns: [] };
  const ctx = { calculator: "PLL/Clock", hse: parseFloat(hse), sysclk: fmtHz(pl.sysclk), style: pl.style };
  const summary = `${profile.name} → ${fmtHz(pl.sysclk)}`;
  useEffect(() => { onCalc({ tab: "pll", mcuKey: profileKey, mcu: profile.name, summary, ctx, inputs: { hse, m, n, p, q }, time: ts() }); }, [hse, m, n, p, q, profileKey, profile.name]);
  const showStm32Pll = profile.pllStyle === "stm32";
  const showGenericPll = profile.pllStyle === "rp2040";
  const showEsp32 = profile.pllStyle === "esp32";
  return (
    <div style={{display:"flex",flexDirection:"column",gap:11}}>
      <ProfileSdkNote profile={profile}/>
      {profile.pllStyle === "none" && <Warn msg="No PLL on this MCU — F_CPU drives all peripherals. Use UART/Timer tabs with 16 MHz (or your crystal)."/>}
      {showStm32Pll && (
        <div className="calc-grid-3" style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:10}}>
          <Field label="HSE (MHz)" value={hse} onChange={setHse} unit="MHz"/>
          <Field label="÷M" value={m} onChange={setM} hint="2–63"/>
          <Field label="×N" value={n} onChange={setN} hint="50–432"/>
          <Field label="÷P (SYSCLK)" value={p} onChange={setP} hint="2,4,6,8"/>
          <Field label="÷Q (USB)" value={q} onChange={setQ} hint="2–15"/>
        </div>
      )}
      {showEsp32 && (
        <div className="calc-grid-2" style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
          <Field label="CPU (MHz)" value={String(pl.cpuMHz || 240)} onChange={()=>{}} unit="MHz" hint="Typical ESP-IDF default"/>
          <Field label="APB / UART clk (MHz)" value={String(pl.apbMHz || 80)} onChange={()=>{}} unit="MHz" hint="CONFIG_ESP_DEFAULT_CPU_FREQ + APB"/>
        </div>
      )}
      {showGenericPll && (
        <div className="calc-grid-3" style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:10}}>
          <Field label="XOSC (MHz)" value={hse} onChange={setHse} unit="MHz"/>
          <Field label="fbdiv" value={n} onChange={setN}/>
          <Field label="postdiv1" value={p} onChange={setP}/>
        </div>
      )}
      {profile.pllStyle === "nordic" && (
        <Field label="HFXO (MHz)" value={hse} onChange={setHse} unit="MHz" hint="32 MHz typical on nRF52840 DK"/>
      )}
      <Divider/>
      <div style={{display:"flex",flexDirection:"column",gap:6}}>
        {pl.vcoIn != null && <Res label="VCO / Ref" value={fmtHz(pl.vcoIn)}/>}
        {pl.vcoOut != null && <Res label="VCO Out" value={fmtHz(pl.vcoOut)}/>}
        <Res label={profile.pllStyle === "none" ? "F_CPU" : "SYSCLK"} value={fmtHz(pl.sysclk)} highlight/>
        {pl.usbClk != null && <Res label="USB / SDIO" value={fmtHz(pl.usbClk)}/>}
        {pl.apb1 != null && <Res label={showEsp32 ? "APB (UART)" : "APB1"} value={fmtHz(pl.apb1)}/>}
        {pl.apb2 != null && !showEsp32 && <Res label="APB2" value={fmtHz(pl.apb2)}/>}
        {pl.hfclk != null && <Res label="HFCLK" value={fmtHz(pl.hfclk)}/>}
      </div>
      {(pl.warns || []).map((w,i)=><Warn key={i} msg={w}/>)}
      {proActive && proKey ? (
        <>
          {profile.pllStyle === "stm32" && <ProClockTreePanel proKey={proKey} proActive={proActive} onUpgrade={onUpgrade} profile={profile} profileKey={profileKey} inputs={{ hse, m, n, p, q }}/>}
          <ProHalExport proKey={proKey} proActive={proActive} onUpgrade={onUpgrade} calculator="pll" profileKey={profileKey} inputs={{ hse, m, n, p, q }} title={sdkExportTitle(profile, profile.pllStyle === "none" ? "clocks.c" : "clock_init.c")}/>
          <AIAssistant context={ctx} licenseKey={proKey}/>
        </>
      ) : <ProGate onUpgrade={onUpgrade}/>}
    </div>
  );
}

function PWMCalc({ profile, profileKey, proActive, proKey, onUpgrade, onCalc, restoreSnap, onRestored }) {
  const [clk,setClk]=useState(String(profile.timerClkMHz ?? profile.maxClock));
  const [freq,setFreq]=useState("50");
  const [fUnit,setFUnit]=useState("1");
  const [duty,setDuty]=useState("50");
  useRestoreInputs(restoreSnap, "pwm", (inp) => {
    if (inp.clk != null) setClk(String(inp.clk));
    if (inp.freq != null) setFreq(String(inp.freq));
    if (inp.fUnit != null) setFUnit(String(inp.fUnit));
    if (inp.duty != null) setDuty(String(inp.duty));
  }, onRestored);
  const eng = getEngine();
  const pw = eng ? eng.calcPwm(profile, { clk, freq, fUnit, duty }) : { psc: 0, arr: 0, ccr: 0, actualFreq: 0, actualDuty: 0, resolution: 0 };
  const freqHz = parseFloat(freq) * parseFloat(fUnit);
  const dutyN = clamp(parseFloat(duty), 0, 100);
  const ctx = { calculator: "PWM", freqHz, duty: dutyN, psc: pw.psc, arr: pw.arr, ccr: pw.ccr };
  const summary = `${fmtHz(freqHz)} ${dutyN}% → PSC=${pw.psc} ARR=${pw.arr} CCR=${pw.ccr}`;
  useEffect(() => { onCalc({ tab: "pwm", mcuKey: profileKey, mcu: profile.name, summary, ctx, inputs: { clk, freq, fUnit, duty }, time: ts() }); }, [clk, freq, fUnit, duty, profileKey, profile.name]);
  return (
    <div style={{display:"flex",flexDirection:"column",gap:11}}>
      <ProfileSdkNote profile={profile}/>
      <div className="calc-grid-2" style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
        <Field label="Timer Clock" value={clk} onChange={setClk} unit="MHz" hint={`Default ${profile.timerClkMHz} MHz for ${profile.name}`}/>
        <div/>
        <Field label="PWM Frequency" value={freq} onChange={setFreq}/>
        <Sel label="Unit" value={fUnit} onChange={setFUnit} options={[{v:"1000000",l:"MHz"},{v:"1000",l:"kHz"},{v:"1",l:"Hz"}]}/>
        <Field label="Duty Cycle" value={duty} onChange={setDuty} unit="%" hint="0–100"/>
      </div>
      <Divider/>
      <div style={{display:"flex",flexDirection:"column",gap:6}}>
        <Res label="PSC / div" value={pw.psc} highlight copy/>
        <Res label="ARR / wrap" value={pw.arr} highlight copy/>
        <Res label="CCR (Duty)" value={pw.ccr} highlight copy/>
        <Res label="Actual Frequency" value={fmtHz(pw.actualFreq)}/>
        <Res label="Actual Duty" value={pw.actualDuty.toFixed(4)+" %"}/>
        <Res label="Resolution" value={pw.resolution.toFixed(2)+" bits"}/>
      </div>
      <div>
        <div style={{display:"flex",justifyContent:"space-between",fontSize:10,color:T.textMuted,marginBottom:4,fontFamily:T.sans}}>
          <span>Duty Cycle Preview</span><span>{dutyN.toFixed(1)}%</span>
        </div>
        <div style={{height:28,background:T.input,borderRadius:6,overflow:"hidden",border:`1px solid ${T.border}`,position:"relative"}}>
          <div style={{position:"absolute",left:0,top:0,height:"100%",width:`${dutyN}%`,background:`linear-gradient(90deg,${T.accent},${T.accent2})`,transition:"width 0.15s",borderRadius:"6px 0 0 6px"}}/>
          <div style={{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",fontSize:10,color:T.text,fontFamily:T.mono,fontWeight:600}}>{dutyN.toFixed(1)}%</div>
        </div>
      </div>
      {proActive && proKey ? (
        <>
          <ProHalExport proKey={proKey} proActive={proActive} onUpgrade={onUpgrade} calculator="pwm" profileKey={profileKey} inputs={{ clk, freq, fUnit, duty }} title={sdkExportTitle(profile, "pwm_init.c")}/>
          <AIAssistant context={ctx} licenseKey={proKey}/>
        </>
      ) : <ProGate onUpgrade={onUpgrade}/>}
    </div>
  );
}

function ADCCalc({ profile, profileKey, proActive, proKey, onUpgrade, onCalc, restoreSnap, onRestored }) {
  const defBits = String((profile.adcBits || [12])[0]);
  const defCyc = String((profile.adcSampleCycles || [480])[(profile.adcSampleCycles || []).length - 1] || 480);
  const defClk = profile.family === "avr" ? String(profile.adcMaxClk) : String(Math.min(48, profile.adcMaxClk));
  const [clk,setClk]=useState(defClk);
  const [bits,setBits]=useState(defBits);
  const [cycles,setCycles]=useState(defCyc);
  const [vref,setVref]=useState("3.3");
  const [raw,setRaw]=useState("2048");
  useRestoreInputs(restoreSnap, "adc", (inp) => {
    if (inp.clk != null) setClk(String(inp.clk));
    if (inp.bits != null) setBits(String(inp.bits));
    if (inp.cycles != null) setCycles(String(inp.cycles));
    if (inp.vref != null) setVref(String(inp.vref));
    if (inp.raw != null) setRaw(String(inp.raw));
  }, onRestored);
  const eng = getEngine();
  const ad = eng ? eng.calcAdc(profile, { clk, bits, cycles, vref, raw }) : { convTime: 0, sRate: 0, lsb: 0, maxRaw: 0, voltage: 0 };
  const bitsN = parseFloat(bits);
  const vrefN = parseFloat(vref);
  const rawN = parseFloat(raw);
  const pct = (rawN / ad.maxRaw) * 100;
  const bitOpts = (profile.adcBits || [12]).map((b) => ({ v: String(b), l: `${b}-bit` }));
  const ctx = { calculator: "ADC", clkMHz: parseFloat(clk), bits: bitsN, sampleRate: fmtHz(ad.sRate), lsb_mV: (ad.lsb * 1000).toFixed(3) };
  const summary = `${bitsN}-bit ADC → ${fmtHz(ad.sRate)}`;
  useEffect(() => { onCalc({ tab: "adc", mcuKey: profileKey, mcu: profile.name, summary, ctx, inputs: { clk, bits, cycles, vref, raw }, time: ts() }); }, [clk, bits, cycles, vref, raw, profileKey, profile.name]);
  return (
    <div style={{display:"flex",flexDirection:"column",gap:11}}>
      <ProfileSdkNote profile={profile}/>
      <div className="calc-grid-2" style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
        <Field label="ADC Clock" value={clk} onChange={setClk} unit="MHz" hint={`Max ${profile.adcMaxClk} MHz`}/>
        <Sel label="Resolution" value={bits} onChange={setBits} options={bitOpts}/>
        <Field label="Sample Cycles" value={cycles} onChange={setCycles} hint={profile.family === "avr" ? "13 cycles fixed" : profile.family === "rp2040" ? "96 typical" : ""}/>
        <Field label="VREF+" value={vref} onChange={setVref} unit="V"/>
      </div>
      <Divider/>
      <div style={{display:"flex",flexDirection:"column",gap:6}}>
        <Res label="Conversion Time" value={fmtTime(ad.convTime)} highlight/>
        <Res label="Max Sample Rate" value={fmtHz(ad.sRate)} highlight/>
        <Res label="LSB Size" value={(ad.lsb*1000).toFixed(3)+" mV"}/>
        <Res label="Max Raw Value" value={ad.maxRaw}/>
      </div>
      <div style={{borderTop:`1px solid ${T.border}`,paddingTop:10}}>
        <p style={{fontSize:10,color:T.textMuted,marginBottom:7,textTransform:"uppercase",letterSpacing:"0.1em",fontFamily:T.sans}}>Raw → Voltage Converter</p>
        <Field label={`Raw Value (0–${ad.maxRaw})`} value={raw} onChange={setRaw}/>
        <div style={{height:8}}/>
        <Res label="Voltage" value={isFinite(ad.voltage)?ad.voltage.toFixed(4)+" V":"—"} highlight/>
        <div style={{height:8}}/>
        <div style={{height:12,background:T.input,borderRadius:4,overflow:"hidden",border:`1px solid ${T.border}`}}>
          <div style={{width:`${clamp(pct,0,100)}%`,height:"100%",background:`linear-gradient(90deg,${T.accent3},${T.accent})`,transition:"width 0.15s"}}/>
        </div>
        <p style={{fontSize:10,color:T.textMuted,textAlign:"right",marginTop:3,fontFamily:T.sans}}>{pct.toFixed(2)}% of full scale</p>
      </div>
      {proActive && proKey ? (
        <>
          <ProHalExport proKey={proKey} proActive={proActive} onUpgrade={onUpgrade} calculator="adc" profileKey={profileKey} inputs={{ clk, bits, cycles, vref }} title={sdkExportTitle(profile, "adc_init.c")}/>
          <AIAssistant context={ctx} licenseKey={proKey}/>
        </>
      ) : <ProGate onUpgrade={onUpgrade}/>}
    </div>
  );
}

function BusCalc({ profile, profileKey, proActive, proKey, onUpgrade, onCalc, restoreSnap, onRestored }) {
  const [bus,setBus]=useState("i2c");
  const [clk,setClk]=useState(String(profile.busClkMHz ?? 42));
  const [ccr,setCcr]=useState("210");
  const [bytes,setBytes]=useState("10");
  useRestoreInputs(restoreSnap, "bus", (inp) => {
    if (inp.bus != null) setBus(String(inp.bus));
    if (inp.clk != null) setClk(String(inp.clk));
    if (inp.ccr != null) setCcr(String(inp.ccr));
    if (inp.bytes != null) setBytes(String(inp.bytes));
  }, onRestored);
  const eng = getEngine();
  const bs = eng ? eng.calcBus(profile, { bus, clk, ccr, bytes }) : { freq: 0, txTime: 0, throughput: 0, regLabel: "CCR", reg: 0, isI2C: bus === "i2c" };
  const ccrN = parseFloat(ccr);
  const ctx = { calculator: bus.toUpperCase(), clkMHz: parseFloat(clk), busFreq: fmtHz(bs.freq), throughput: bs.throughput.toFixed(2) + " kB/s" };
  const summary = `${bus.toUpperCase()} ${clk}MHz ${bs.regLabel}=${ccrN} → ${fmtHz(bs.freq)}`;
  useEffect(() => { onCalc({ tab: "bus", mcuKey: profileKey, mcu: profile.name, summary, ctx, inputs: { bus, clk, ccr, bytes }, time: ts() }); }, [bus, clk, ccr, bytes, profileKey, profile.name]);
  return (
    <div style={{display:"flex",flexDirection:"column",gap:11}}>
      <ProfileSdkNote profile={profile}/>
      <div style={{display:"flex",gap:6}}>
        {["i2c","spi"].map(b=><button key={b} onClick={()=>setBus(b)} style={{padding:"5px 18px",borderRadius:6,border:`1px solid ${bus===b?T.accent:T.border}`,background:bus===b?T.accent+"18":"transparent",color:bus===b?T.accent:T.textMuted,cursor:"pointer",fontSize:12,fontFamily:T.sans,fontWeight:600,textTransform:"uppercase"}}>{b}</button>)}
      </div>
      <div className="calc-grid-2" style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
        <Field label="Bus Clock" value={clk} onChange={setClk} unit="MHz" hint={`Default ${profile.busClkMHz} MHz`}/>
        <Field label={bs.regLabel} value={ccr} onChange={setCcr} hint={profile.family === "avr" && bus === "i2c" ? "TWBR" : ""}/>
        <Field label="Byte Count" value={bytes} onChange={setBytes} hint="For transfer time calc"/>
      </div>
      <Divider/>
      <div style={{display:"flex",flexDirection:"column",gap:6}}>
        <Res label="Bus Rate" value={fmtHz(bs.freq)} highlight/>
        <Res label="Transfer Time" value={fmtTime(bs.txTime)} highlight/>
        <Res label="Throughput" value={isFinite(bs.throughput)?bs.throughput.toFixed(2)+" kB/s":"—"}/>
      </div>
      {bs.isI2C && bs.freq > (profile.i2cMaxHz || 400000) && <Warn msg={`Exceeds ${(profile.i2cMaxHz || 400000) / 1000} kHz I²C max for ${profile.name}.`}/>}
      {proActive && proKey ? (
        <>
          <ProHalExport proKey={proKey} proActive={proActive} onUpgrade={onUpgrade} calculator="bus" profileKey={profileKey} inputs={{ bus, clk, ccr, bytes }} title={sdkExportTitle(profile, `${bus}_init.c`)}/>
          <AIAssistant context={ctx} licenseKey={proKey}/>
        </>
      ) : <ProGate onUpgrade={onUpgrade}/>}
    </div>
  );
}

// ─── TABS ─────────────────────────────────────────────────────────────────────
const TABS = [
  {id:"baud",  label:"UART",    icon:"↔",  badge:"#38bdf8", comp:BaudCalc},
  {id:"timer", label:"Timer",   icon:"⏱",  badge:"#34d399", comp:TimerCalc},
  {id:"pll",   label:"PLL",     icon:"⚙️",  badge:"#c084fc", comp:PLLCalc},
  {id:"pwm",   label:"PWM",     icon:"📶",  badge:"#fbbf24", comp:PWMCalc},
  {id:"adc",   label:"ADC",     icon:"〰️",  badge:"#4ade80", comp:ADCCalc},
  {id:"bus",   label:"I²C/SPI", icon:"🔌", badge:"#818cf8", comp:BusCalc},
];

// ─── USAGE COUNTER NUDGE ─────────────────────────────────────────────────────
function UsageNudge({ count, onUpgrade, isPro }) {
  if (isPro || count < 3) return null;
  const savings = Math.round(count * 0.4);
  return (
    <div style={{background:`linear-gradient(90deg,${T.gold}0a,${T.accent2}08)`,border:`1px solid ${T.gold}1a`,borderRadius:8,padding:"9px 14px",marginBottom:12,display:"flex",alignItems:"center",justifyContent:"space-between",gap:10}}>
      <p style={{fontSize:12,color:T.textMid,fontFamily:T.sans,margin:0}}>
        <span style={{color:T.gold,fontWeight:700}}>⚡ {count} calculations today</span>
        {" "}— PRO users save ~{savings} min/day with instant code export.
      </p>
      <button onClick={onUpgrade} style={{padding:"5px 12px",background:`linear-gradient(135deg,${T.gold},#ef4444)`,border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:11,fontWeight:700,fontFamily:T.sans,whiteSpace:"nowrap",flexShrink:0}}>
        Get PRO
      </button>
    </div>
  );
}

// ─── MAIN APP ─────────────────────────────────────────────────────────────────
function App() {
  const [activeTab,   setActiveTab]   = useState("baud");
  const [mcuKey,      setMcuKey]      = useState("stm32f4");
  const [isPro,       setIsPro]       = useState(false);
  const [proKey,      setProKey]      = useState("");
  const [showPricing, setShowPricing] = useState(false);
  const [showExit,    setShowExit]    = useState(false);
  const [showHistory, setShowHistory] = useState(false);
  const [showExport,  setShowExport]  = useState(false);
  const [exportData,  setExportData]  = useState(null);
  const [history,     setHistory]     = useState([]);
  const [historySelected, setHistorySelected] = useState(0);
  const [historyPreview, setHistoryPreview] = useState(null);
  const [restoreSnap, setRestoreSnap] = useState(null);
  const [calcCount,   setCalcCount]   = useState(0);
  const exitShown = useRef(false);

  useEffect(() => {
    try {
      const raw = localStorage.getItem(HISTORY_STORAGE_KEY);
      if (raw) {
        const parsed = JSON.parse(raw);
        if (Array.isArray(parsed) && parsed.length) {
          const migrated = parsed.map(e => ({
            ...e,
            tab: normalizeHistoryTab(e.tab),
            mcuKey: e.mcuKey || mcuKeyFromProfileName(e.mcu),
          }));
          setHistory(migrated);
          setHistoryPreview(migrated[0]);
        }
      }
    } catch (_) {}
  }, []);

  useEffect(() => {
    try {
      if (history.length) localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(history));
    } catch (_) {}
  }, [history]);

  useEffect(() => {
    const key = localStorage.getItem("regcalc_pro_key");
    if (!key) return;
    establishProSession(key)
      .then(({ key: k }) => { setProKey(k); setIsPro(true); })
      .catch(() => {
        localStorage.removeItem("regcalc_pro_key");
        setProKey("");
        setIsPro(false);
      });
  }, []);

  const profiles = getMcuProfiles();
  const profile = profiles[mcuKey];
  const tab = TABS.find(x => x.id === activeTab) || TABS[0];
  const Comp = tab.comp;

  useEffect(() => {
    if (!TABS.some(t => t.id === activeTab)) setActiveTab("baud");
  }, [activeTab]);

  const clearRestore = useCallback(() => setRestoreSnap(null), []);

  // Exit intent
  useEffect(() => {
    if (isPro) return;
    const handler = e => {
      if (e.clientY < 30 && !exitShown.current && calcCount >= 2) {
        exitShown.current = true;
        setShowExit(true);
      }
    };
    document.addEventListener("mousemove", handler);
    return () => document.removeEventListener("mousemove", handler);
  }, [isPro, calcCount]);

  // Keyboard shortcuts
  useEffect(() => {
    const kh = e => {
      if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA" || e.target.tagName === "SELECT") return;
      const idx = TABS.findIndex(t => t.id === activeTab);
      if (e.key === "ArrowRight" || e.key === "]") setActiveTab(TABS[(idx+1)%TABS.length].id);
      if (e.key === "ArrowLeft"  || e.key === "[") setActiveTab(TABS[(idx-1+TABS.length)%TABS.length].id);
      if (e.key === "h" || e.key === "H") setShowHistory(s=>!s);
      if (e.key === "p" || e.key === "P") !isPro && setShowPricing(true);
      if (e.key === "Escape") { setShowHistory(false); setShowPricing(false); setShowExit(false); }
    };
    window.addEventListener("keydown", kh);
    return () => window.removeEventListener("keydown", kh);
  }, [activeTab, isPro]);

  const handleCalc = useCallback(entry => {
    const normalized = { ...entry, tab: normalizeHistoryTab(entry.tab) };
    setHistory(h => {
      const deduped = h.filter(x => !(x.tab === normalized.tab && x.mcu === normalized.mcu && x.summary === normalized.summary));
      return [normalized, ...deduped].slice(0, 20);
    });
    setCalcCount(c => c + 1);
  }, []);

  const handleHistorySelect = useCallback((id, entry) => {
    setHistorySelected(id);
    setHistoryPreview(entry);
  }, []);

  const handleRestore = useCallback(entry => {
    const tabId = normalizeHistoryTab(entry.tab);
    if (!TABS.some(t => t.id === tabId)) return;
    setActiveTab(tabId);
    const key = entry.mcuKey || mcuKeyFromProfileName(entry.mcu);
    if (key && getMcuProfiles()[key]) setMcuKey(key);
    if (entry.inputs && Object.keys(entry.inputs).length > 0) {
      setRestoreSnap({ tab: tabId, inputs: entry.inputs, nonce: Date.now() });
    }
    setHistoryPreview(entry);
  }, []);

  return (
    <div style={{minHeight:"100vh",background:T.bg,color:T.text,fontFamily:T.sans,overflowX:"hidden",maxWidth:"100vw"}}>
      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700&family=JetBrains+Mono:wght@400;600&display=swap');
        html,body{overflow-x:hidden;max-width:100vw}
        *{box-sizing:border-box;margin:0;padding:0;min-width:0}
        ::-webkit-scrollbar{width:5px;height:5px}
        ::-webkit-scrollbar-track{background:transparent}
        ::-webkit-scrollbar-thumb{background:${T.border};border-radius:4px}
        input[type=number]::-webkit-inner-spin-button{-webkit-appearance:none}
        input,select,textarea{min-width:0;max-width:100%}
        @keyframes pulse{0%,100%{transform:scale(.7);opacity:.4}50%{transform:scale(1);opacity:1}}
        @keyframes slideIn{from{opacity:0;transform:translateX(100%)}to{opacity:1;transform:translateX(0)}}
        a:focus-visible,button:focus-visible{outline:2px solid ${T.accent};outline-offset:2px;border-radius:4px}
        @media(max-width:520px){
          .mcu-header-row{flex-wrap:wrap;gap:6px!important;padding:10px 0 6px!important}
          .mcu-header-brand{flex:1;min-width:0}
          .mcu-header-right{width:100%;justify-content:space-between}
          .mcu-header-right select{flex:1;min-width:0;max-width:200px;font-size:11px!important}
          .mcu-feature-strip{flex-wrap:wrap}
          .mcu-feature-strip .max-clk{display:none}
          .tab-icon{display:none}
          .calc-grid-2{grid-template-columns:1fr!important}
          .calc-grid-3{grid-template-columns:1fr 1fr!important}
          .promo-banner{flex-direction:column!important;align-items:flex-start!important;gap:8px!important}
          .promo-banner button{width:100%}
          .fvp-feat{padding:8px 10px!important;font-size:11px!important}
          .fvp-val{padding:8px 6px!important;font-size:12px!important}
          .plan-btns{flex-direction:column!important}
          .plan-btns button{flex:none!important;width:100%!important}
          .checkout-row{flex-direction:column!important}
          .checkout-row>div{flex:none!important;width:100%!important}
          .modal-header{padding:16px 16px 0!important}
          .modal-body{padding:16px!important}
          .tab-mode-row{flex-direction:column!important;align-items:stretch!important}
          .tab-mode-row button{text-align:center}
          .history-panel{width:100%!important;border-radius:0!important}
        }
      `}</style>

      {showPricing && <PricingModal onClose={()=>setShowPricing(false)} onSuccess={(key)=>{ if(key){ setProKey(key); setIsPro(true); } setShowPricing(false); }}/>}
      {showExit    && <ExitModal onClose={()=>setShowExit(false)} onUpgrade={()=>{ setShowExit(false); setShowPricing(true); }}/>}
      {showExport  && <ExportModal data={exportData} onClose={()=>setShowExport(false)}/>}

      {/* HISTORY DRAWER */}
      {showHistory && (
        <div style={{position:"fixed",top:0,right:0,bottom:0,width:340,background:T.surface,borderLeft:`1px solid ${T.border}`,zIndex:150,display:"flex",flexDirection:"column",animation:"slideIn .25s ease",boxShadow:"-20px 0 40px rgba(0,0,0,.4)"}} className="history-panel">
          <div style={{padding:"16px",borderBottom:`1px solid ${T.border}`,display:"flex",justifyContent:"space-between",alignItems:"center"}}>
            <h3 style={{fontSize:14,fontWeight:700,fontFamily:T.sans}}>Historija</h3>
            <div style={{display:"flex",gap:8}}>
              <button onClick={()=>{if(history.length>0){setExportData({calculations:history,exportedAt:new Date().toISOString()});setShowExport(true);}}} style={{fontSize:11,color:T.textMuted,background:"none",border:`1px solid ${T.border}`,borderRadius:5,padding:"3px 9px",cursor:"pointer",fontFamily:T.sans}}>↓ Export</button>
              <button onClick={()=>setShowHistory(false)} style={{background:"none",border:"none",color:T.textMuted,cursor:"pointer",fontSize:18,lineHeight:1}}>×</button>
            </div>
          </div>
          <div style={{flex:1,overflowY:"auto",display:"flex",flexDirection:"column",minHeight:0}}>
            <HistoryPanel history={history} selectedId={historySelected} onSelect={handleHistorySelect} onRestore={handleRestore}/>
            <HistoryDetail entry={historyPreview}/>
          </div>
          <div style={{padding:"10px 14px",borderTop:`1px solid ${T.border}`,fontSize:10,color:T.textMuted,fontFamily:T.mono,textAlign:"center"}}>
            H — panel · klik — učitaj u kalkulator
          </div>
        </div>
      )}

      {/* HEADER */}
      <header style={{background:T.surface,borderBottom:`1px solid ${T.border}`,padding:"0 clamp(12px,4vw,20px)",position:"sticky",top:0,zIndex:100}}>
        <div style={{maxWidth:APP_MAX_W,margin:"0 auto",minWidth:0}}>
          <div className="mcu-header-row" style={{display:"flex",alignItems:"center",gap:12,padding:"14px 0 0"}}>
            <svg width="36" height="36" viewBox="0 0 60 60" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="rcg2" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stopColor="#38bdf8"/><stop offset="100%" stopColor="#2563eb"/></linearGradient><filter id="rcglow3"><feGaussianBlur stdDeviation="1.5" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge></filter><filter id="rcglow4"><feGaussianBlur stdDeviation="3" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge></filter></defs><rect x="4" y="4" width="52" height="52" rx="8" fill="none" stroke="url(#rcg2)" strokeWidth="2" filter="url(#rcglow4)" opacity="0.9"/><line x1="4" y1="21" x2="56" y2="21" stroke="url(#rcg2)" strokeWidth="0.8" opacity="0.4"/><line x1="4" y1="39" x2="56" y2="39" stroke="url(#rcg2)" strokeWidth="0.8" opacity="0.4"/><line x1="21" y1="4" x2="21" y2="56" stroke="url(#rcg2)" strokeWidth="0.8" opacity="0.4"/><line x1="39" y1="4" x2="39" y2="56" stroke="url(#rcg2)" strokeWidth="0.8" opacity="0.4"/><rect x="12" y="12" width="8" height="8" rx="2" fill="url(#rcg2)" filter="url(#rcglow3)"/><rect x="26" y="12" width="8" height="8" rx="2" fill="url(#rcg2)" filter="url(#rcglow3)" opacity="0.8"/><rect x="40" y="12" width="8" height="8" rx="2" fill="url(#rcg2)" filter="url(#rcglow3)"/><rect x="12" y="26" width="8" height="8" rx="2" fill="url(#rcg2)" filter="url(#rcglow3)" opacity="0.8"/><rect x="24" y="24" width="12" height="12" rx="3" fill="url(#rcg2)" filter="url(#rcglow4)"/><rect x="40" y="26" width="8" height="8" rx="2" fill="url(#rcg2)" filter="url(#rcglow3)" opacity="0.8"/><rect x="12" y="40" width="8" height="8" rx="2" fill="url(#rcg2)" filter="url(#rcglow3)"/><rect x="26" y="40" width="8" height="8" rx="2" fill="url(#rcg2)" filter="url(#rcglow3)" opacity="0.8"/><rect x="40" y="40" width="8" height="8" rx="2" fill="url(#rcg2)" filter="url(#rcglow3)"/></svg>
            <div className="mcu-header-brand" style={{minWidth:0,flex:1}}>
              <div style={{display:"flex",alignItems:"center",gap:8}}>
                <span style={{fontWeight:700,fontSize:16,letterSpacing:"-0.03em"}}>RegCalc</span>
                {isPro
                  ? <span style={{background:"linear-gradient(135deg,#f59e0b,#ef4444)",borderRadius:4,padding:"2px 8px",fontSize:10,fontWeight:700,color:"#fff",letterSpacing:"0.05em"}}>PRO</span>
                  : <span style={{border:`1px solid ${T.border}`,borderRadius:4,padding:"2px 8px",fontSize:10,fontWeight:600,color:T.textMuted,letterSpacing:"0.05em"}}>FREE</span>
                }
              </div>
              <span style={{fontSize:11,color:T.textMuted}}>Embedded Systems Toolkit</span>
            </div>
            <div className="mcu-header-right" style={{marginLeft:"auto",display:"flex",alignItems:"center",gap:8}}>
              {/* History button */}
              <button onClick={()=>setShowHistory(s=>!s)} title="History (H)"
                style={{padding:"6px 10px",background:showHistory?T.accent+"18":"transparent",border:`1px solid ${showHistory?T.accent+"44":T.border}`,borderRadius:7,color:showHistory?T.accent:T.textMuted,cursor:"pointer",fontSize:12,fontFamily:T.sans,display:"flex",alignItems:"center",gap:4,position:"relative"}}>
                🕐
                {history.length>0&&<span style={{position:"absolute",top:-4,right:-4,width:14,height:14,background:T.accent,borderRadius:"50%",fontSize:8,color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:700}}>{Math.min(history.length,9)}</span>}
              </button>
              <select value={mcuKey} onChange={e=>setMcuKey(e.target.value)}
                style={{background:T.input,border:`1px solid ${T.border}`,borderRadius:7,color:T.text,padding:"6px 10px",fontSize:12,outline:"none",fontFamily:T.mono,cursor:"pointer",minWidth:0,maxWidth:"100%"}}>
                {Object.entries(getMcuProfiles()).map(([k,v])=><option key={k} value={k}>{v.name}</option>)}
              </select>
              {isPro ? (
                <div style={{padding:"6px 12px",background:T.goldGlow,border:`1px solid ${T.gold}44`,borderRadius:7,color:T.gold,fontSize:11,fontWeight:700,fontFamily:T.sans}}>✓ PRO Active</div>
              ) : (
                <button onClick={()=>setShowPricing(true)}
                  style={{padding:"6px 16px",background:"linear-gradient(135deg,#f59e0b,#ef4444)",border:"none",borderRadius:7,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:700,whiteSpace:"nowrap",fontFamily:T.sans,boxShadow:"0 2px 12px #f59e0b33"}}>
                  Get PRO ↗
                </button>
              )}
            </div>
          </div>

          {/* MCU feature strip */}
          <div className="mcu-feature-strip" style={{display:"flex",gap:6,padding:"8px 0 0",flexWrap:"wrap",alignItems:"center"}}>
            <span style={{fontSize:10,color:profile.color,fontFamily:T.mono,fontWeight:700,marginRight:2}}>{profile.vendor}</span>
            {(profile.features || []).map(f=>(
              <span key={f} style={{fontSize:10,color:profile.color,background:profile.color+"12",border:`1px solid ${profile.color}2a`,borderRadius:4,padding:"2px 7px",fontFamily:T.mono}}>{f}</span>
            ))}
            {profile.codeSdk && (
              <span style={{fontSize:10,color:T.accent,fontFamily:T.mono,background:T.accent+"18",border:`1px solid ${T.accent}44`,borderRadius:4,padding:"2px 7px"}}>{profile.codeSdk}</span>
            )}
            <span className="max-clk" style={{fontSize:10,color:T.textMuted,fontFamily:T.mono,marginLeft:"auto"}}>Max {profile.maxClock} MHz</span>
          </div>

          {/* Tabs */}
          <div style={{display:"flex",marginTop:10,overflowX:"auto",scrollbarWidth:"none",WebkitOverflowScrolling:"touch"}}>
            {TABS.map(t2=>(
              <button key={t2.id} onClick={()=>setActiveTab(t2.id)}
                style={{padding:"9px 12px",border:"none",borderBottom:`2px solid ${activeTab===t2.id?t2.badge:"transparent"}`,background:"transparent",color:activeTab===t2.id?t2.badge:T.textMuted,cursor:"pointer",fontSize:12,fontWeight:600,fontFamily:T.sans,whiteSpace:"nowrap",transition:"all .15s",display:"flex",alignItems:"center",gap:4,flexShrink:0}}>
                <span className="tab-icon" style={{fontSize:12,lineHeight:1}}>{t2.icon}</span>
                <span>{t2.label}</span>
              </button>
            ))}
          </div>
        </div>
      </header>

      {/* MAIN */}
      <main style={{maxWidth:APP_MAX_W,margin:"0 auto",padding:"24px clamp(14px,4vw,20px) 88px"}}>
        <BetaBanner/>
        <UsageNudge count={calcCount} onUpgrade={()=>setShowPricing(true)} isPro={isPro}/>

        {!isPro && (
          <div className="promo-banner" style={{background:`linear-gradient(135deg,${T.gold}0a,${T.accent2}0a)`,border:`1px solid ${T.gold}22`,borderRadius:10,padding:"12px 16px",marginBottom:16,display:"flex",alignItems:"center",justifyContent:"space-between",gap:10}}>
            <div style={{display:"flex",alignItems:"center",gap:10}}>
              <span style={{fontSize:18}}>⚡</span>
              <div>
                <p style={{fontSize:12,fontWeight:600,color:T.text,fontFamily:T.sans,margin:0}}>Unlock HAL code export, AI assistant & clock diagrams</p>
                <p style={{fontSize:11,color:T.textMuted,fontFamily:T.sans,margin:0}}>PRO from $7/month · yearly $49/yr · 30-day refund guarantee</p>
              </div>
            </div>
            <button onClick={()=>setShowPricing(true)}
              style={{padding:"7px 16px",background:`linear-gradient(135deg,${T.gold},#ef4444)`,border:"none",borderRadius:7,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:700,fontFamily:T.sans,whiteSpace:"nowrap",flexShrink:0}}>
              See Plans →
            </button>
          </div>
        )}

        <div style={{background:T.surface,border:`1px solid ${T.border}`,borderRadius:14,padding:"26px 28px"}}>
          <div style={{display:"flex",alignItems:"center",gap:12,marginBottom:20,flexWrap:"wrap"}}>
            <span style={{fontSize:24}}>{tab.icon}</span>
            <h2 style={{fontSize:19,fontWeight:700,letterSpacing:"-0.03em"}}>{tab.label} Calculator</h2>
            <div style={{height:1,flex:1,background:T.border}}/>
            <span style={{fontSize:11,color:T.textMuted,fontFamily:T.mono}}>{profile.name}</span>
          </div>
          <Comp key={mcuKey} profile={profile} profileKey={mcuKey} proActive={isPro && !!proKey} proKey={proKey} onUpgrade={()=>setShowPricing(true)} onCalc={handleCalc} restoreSnap={restoreSnap} onRestored={clearRestore}/>
        </div>

        {!isPro && (
          <div style={{marginTop:20,background:T.surface,border:`1px solid ${T.border}`,borderRadius:12,overflow:"hidden"}}>
            <div style={{padding:"16px 20px",borderBottom:`1px solid ${T.border}`}}>
              <h3 style={{fontSize:14,fontWeight:700,fontFamily:T.sans,color:T.text}}>Free vs PRO</h3>
            </div>
            <div style={{display:"grid",gridTemplateColumns:"2fr 1fr 1fr",borderBottom:`1px solid ${T.border}`}}>
              {["Feature","Free","PRO"].map((h,i)=>(
                <div key={h} className="fvp-feat" style={{padding:"10px 14px",fontSize:10,fontWeight:700,color:i===2?T.gold:T.textMuted,fontFamily:T.sans,textTransform:"uppercase",letterSpacing:"0.08em",background:"transparent",borderLeft:i>0?`1px solid ${T.border}`:"none"}}>{h}</div>
              ))}
            </div>
            <div className="fvp-table" style={{overflowX:"auto"}}>
              {[["All 6 calculators","✓","✓"],["Real-time calculations","✓","✓"],["8 MCU profiles","✓","✓"],["HAL/LL code export","—","✓"],["AI engineer assistant","—","✓"],["Clock tree diagrams","—","✓"],["Register copy-to-clipboard","—","✓"]].map(([feat,free,pro],i)=>(
                <div key={feat} style={{display:"grid",gridTemplateColumns:"2fr 1fr 1fr",borderBottom:i<6?`1px solid ${T.border}`:"none"}}>
                  <div className="fvp-feat" style={{padding:"10px 14px",fontSize:12,color:T.textMid,fontFamily:T.sans}}>{feat}</div>
                  <div className="fvp-val" style={{padding:"10px 14px",fontSize:13,color:free==="✓"?T.accent3:T.textMuted,fontFamily:T.mono,fontWeight:500,borderLeft:`1px solid ${T.border}`,textAlign:"center"}}>{free}</div>
                  <div className="fvp-val" style={{padding:"10px 14px",fontSize:13,color:pro==="✓"?"#f59e0b99":T.textMuted,fontFamily:T.mono,fontWeight:500,borderLeft:`1px solid ${T.border}`,textAlign:"center"}}>{pro}</div>
                </div>
              ))}
            </div>
            <div style={{padding:"16px 20px",background:T.goldGlow,display:"flex",justifyContent:"center"}}>
              <button onClick={()=>setShowPricing(true)}
                style={{padding:"10px 28px",background:"linear-gradient(135deg,#f59e0b,#ef4444)",border:"none",borderRadius:8,color:"#fff",cursor:"pointer",fontSize:13,fontWeight:700,fontFamily:T.sans}}>
                Upgrade to PRO — from $7/month →
              </button>
            </div>
          </div>
        )}
      </main>

      <footer style={{textAlign:"center",padding:"20px 16px",borderTop:`1px solid ${T.border}`,color:T.textMuted,fontSize:11,fontFamily:T.sans}}>
        <span>RegCalc</span>
        <span style={{margin:"0 8px",opacity:.3}}>·</span>
        <span>All calculations real-time</span>
        <span style={{margin:"0 8px",opacity:.3}}>·</span>
        <span>© 2026</span>
        <span style={{margin:"0 8px",opacity:.3}}>·</span>
        <span style={{fontFamily:T.mono,fontSize:10,color:T.textMuted}}>← → or [ ] switch tabs · H history · P pricing · Esc close</span>
        {!isPro&&(
          <span> · <button onClick={()=>setShowPricing(true)} style={{background:"none",border:"none",color:T.gold,cursor:"pointer",fontSize:11,fontFamily:T.sans,fontWeight:600}}>Upgrade to PRO</button></span>
        )}
      </footer>
    </div>
  );
}
