// Calc-U 59 — Faithful recreation of the iOS app UI.
// Reference: assets/app-screenshot.png. Numeric ops work; many program-mode
// keys are decorative. This component is the centerpiece of the UI kit.

const { useState: useStateCalc } = React;

function Calculator({ scale = 1 }) {
  const [display, setDisplay] = useStateCalc("-1,234567 8-90");
  const [acc, setAcc] = useStateCalc(null);
  const [op,  setOp]  = useStateCalc(null);
  const [fresh, setFresh] = useStateCalc(true);
  const [shift, setShift] = useStateCalc(null);

  const press = (k) => {
    if (k === "2nd") { setShift(shift === "2nd" ? null : "2nd"); return; }
    if (k === "INV") { setShift(shift === "INV" ? null : "INV"); return; }
    if (k === "CLR") { setDisplay("0."); setAcc(null); setOp(null); setFresh(true); setShift(null); return; }
    if (k === "CE")  { setDisplay("0."); setFresh(true); setShift(null); return; }

    if (/^[0-9]$/.test(k)) {
      const next = fresh || display === "0." || /[-,a-z]/i.test(display)
        ? k + "."
        : (display.endsWith(".") ? display.slice(0, -1) + k + "." : display + k);
      setDisplay(next);
      setFresh(false);
      setShift(null);
      return;
    }
    if (k === ".") {
      if (!display.includes(".") || fresh) {
        setDisplay(fresh ? "0." : display.endsWith(".") ? display : display + ".");
        setFresh(false);
      }
      setShift(null);
      return;
    }
    if (k === "+/-") {
      const n = parseFloat(display);
      if (!isNaN(n)) setDisplay(formatLED(-n));
      setShift(null);
      return;
    }
    if (["+","-","×","÷"].includes(k)) {
      const cur = parseFloat(display);
      const next = (acc == null || op == null || isNaN(cur)) ? (isNaN(cur) ? 0 : cur) : applyOp(acc, cur, op);
      setAcc(next); setDisplay(formatLED(next)); setOp(k); setFresh(true); setShift(null);
      return;
    }
    if (k === "=") {
      const cur = parseFloat(display);
      const next = (acc == null || op == null) ? cur : applyOp(acc, cur, op);
      setDisplay(formatLED(next)); setAcc(null); setOp(null); setFresh(true); setShift(null);
      return;
    }
    if (k === "√x")    { setDisplay(formatLED(Math.sqrt(parseFloat(display)||0))); setFresh(true); setShift(null); return; }
    if (k === "x²")    { setDisplay(formatLED(Math.pow(parseFloat(display)||0,2))); setFresh(true); setShift(null); return; }
    if (k === "1/x")   { setDisplay(formatLED(1/(parseFloat(display)||1))); setFresh(true); setShift(null); return; }
    if (k === "lnx")   { setDisplay(formatLED(Math.log(parseFloat(display)||1))); setFresh(true); setShift(null); return; }
    setShift(null);
  };

  // ---- Key bank ----
  // tone: cream | dark | yellow
  // top labels: their color hints (silk-cream / silk-yellow / silk-mahogany)
  const D = "dark", C = "cream", Y = "yellow";
  const rows = [
    [
      {top:"A'",label:"A",tone:D}, {top:"B'",label:"B",tone:D},
      {top:"C'",label:"C",tone:D}, {top:"D'",label:"D",tone:D}, {top:"E'",label:"E",tone:D}
    ],
    [
      {top:"",label:"2nd",tone:Y}, {top:"",label:"INV",tone:D},
      {top:"log",label:"lnx",tone:D}, {top:"CP",label:"CE",tone:D}, {top:"",label:"CLR",tone:Y}
    ],
    [
      {top:"Pgm",label:"LRN",tone:D}, {top:"P→R",label:"x⇄t",tone:D},
      {top:"sin",label:"x²",tone:D}, {top:"cos",label:"√x",tone:D}, {top:"tan",label:"1/x",tone:D}
    ],
    [
      {top:"Ins",label:"SST",tone:D}, {top:"CMs",label:"STO",tone:D},
      {top:"Exc",label:"RCL",tone:D}, {top:"Prd",label:"SUM",tone:D}, {top:"Ind",label:"yˣ",tone:D}
    ],
    [
      {top:"Del",label:"BST",tone:D}, {top:"Eng",label:"EE",tone:D},
      {top:"Fix",label:"(",tone:D}, {top:"Int",label:")",tone:D}, {top:"|x|",label:"÷",tone:Y}
    ],
    [
      {top:"Pause",label:"GTO",tone:D}, {top:"x=t",label:"7",tone:C},
      {top:"Nop",label:"8",tone:C}, {top:"Op",label:"9",tone:C}, {top:"Deg",label:"×",tone:Y}
    ],
    [
      {top:"Lbl",label:"SBR",tone:D}, {top:"x≥t",label:"4",tone:C},
      {top:"Σ+",label:"5",tone:C}, {top:"x̄",label:"6",tone:C}, {top:"Rad",label:"−",tone:Y}
    ],
    [
      {top:"St flg",label:"RST",tone:D}, {top:"If flg",label:"1",tone:C},
      {top:"D.MS",label:"2",tone:C}, {top:"π",label:"3",tone:C}, {top:"Grad",label:"+",tone:Y}
    ],
    [
      {top:"Write",label:"R/S",tone:D}, {top:"Dsz",label:"0",tone:C},
      {top:"Adv",label:".",tone:C}, {top:"Prt",label:"+/-",tone:C}, {top:"List",label:"=",tone:Y}
    ],
  ];

  return (
    <div className="calcu-device" style={{
      width: `${360 * scale}px`,
      background: "#000",
      padding: `${10*scale}px ${12*scale}px ${8*scale}px`,
      fontFamily: "var(--font-key)",
      userSelect: "none",
    }}>
      {/* Display block (mahogany strip + LED + module header panel) */}
      <Display scale={scale} text={display} shift={shift} />

      {/* Key grid */}
      <div style={{ display: "grid", gap: 8 * scale, marginTop: 14 * scale }}>
        {rows.map((row, ri) => (
          <div key={ri} style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 8 * scale }}>
            {row.map((kc, ci) => <CalcKey key={ci} kc={kc} scale={scale} onPress={press} />)}
          </div>
        ))}
      </div>

      {/* iOS-style bottom toolbar */}
      <BottomToolbar scale={scale} />
    </div>
  );
}

/* ============================================================
   Display — mahogany strip + LED window + module reference panel
   ============================================================ */
function Display({ scale, text, shift }) {
  return (
    <div style={{
      background: "linear-gradient(180deg,#1a0c08 0%,#2c1812 50%,#1a0c08 100%)",
      borderRadius: 10 * scale,
      padding: `${10*scale}px ${10*scale}px ${0}px`,
      border: `1px solid #3a2418`,
      boxShadow: "0 1px 0 rgba(255,200,100,.04), inset 0 0 0 1px rgba(0,0,0,.4)",
      position: "relative",
    }}>
      {/* LED window */}
      <div style={{
        background: "#0a0302",
        borderRadius: 4 * scale,
        padding: `${10*scale}px ${12*scale}px ${4*scale}px`,
        position: "relative",
        boxShadow: "inset 0 2px 8px rgba(0,0,0,.8)",
        overflow: "hidden",
      }}>
        <div style={{
          position: "absolute", inset: `${10*scale}px ${12*scale}px ${4*scale}px`,
          fontFamily: "var(--font-display)",
          fontSize: 26 * scale,
          color: "#3a0e08",
          letterSpacing: ".04em",
          textAlign: "right",
          lineHeight: 1,
          whiteSpace: "nowrap",
          overflow: "hidden",
        }}>~8.8.8.8.8.8.8.8-8.8.</div>
        <div style={{
          position: "relative",
          fontFamily: "var(--font-display)",
          fontSize: 26 * scale,
          color: "#ff2614",
          textShadow: "0 0 10px rgba(255,38,20,.7), 0 0 22px rgba(255,38,20,.3)",
          letterSpacing: ".04em",
          textAlign: "right",
          lineHeight: 1,
          whiteSpace: "nowrap",
          overflow: "hidden",
        }}>{text}</div>

        {/* Watermarks: Solid State Software / TI ©1977 */}
        <div style={{
          display: "flex", justifyContent: "space-between",
          marginTop: 6 * scale,
          color: "#5a3018",
          fontFamily: "var(--font-key)",
          fontSize: 9 * scale,
          letterSpacing: ".12em",
          textTransform: "uppercase",
        }}>
          <span>Solid State Software</span>
          <span>TI ©1977</span>
        </div>
      </div>

      {/* Module header strip — "MASTER LIBRARY DIAGNOSTIC  ML-01" */}
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        padding: `${8*scale}px 2px ${2*scale}px`,
        color: "#c89858",
        fontFamily: "var(--font-key)",
        fontWeight: 700,
        fontSize: 11 * scale,
        letterSpacing: ".05em",
      }}>
        <span>MASTER LIBRARY DIAGNOSTIC</span>
        <span>ML-01</span>
      </div>

      {/* Diagnostic instruction lines (per screenshot) */}
      <div style={{
        color: "#a87830",
        fontFamily: "var(--font-key)",
        fontWeight: 500,
        fontSize: 10 * scale,
        letterSpacing: ".04em",
        padding: `${2*scale}px ${2*scale}px ${6*scale}px`,
        lineHeight: 1.6,
      }}>
        <div style={{ textAlign: "center" }}>
          DIAGNOSTIC: <Token scale={scale}>SBR</Token> <Token scale={scale}>=</Token>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 2 }}>
          <span>L.R. INIT: <Token scale={scale}>SBR</Token> <Token scale={scale}>CLR</Token></span>
          <span>PRINT: mm <Token scale={scale}>STO</Token> 00</span>
        </div>
      </div>

      {/* small chevron-right control in top-right (per screenshot) */}
      <div style={{
        position: "absolute", top: 8 * scale, right: 8 * scale,
        width: 24 * scale, height: 24 * scale, borderRadius: 4 * scale,
        background: "rgba(180,140,80,.12)",
        border: "1px solid rgba(180,140,80,.25)",
        display: "flex", alignItems: "center", justifyContent: "center",
        color: "#c89858", fontSize: 14 * scale, fontFamily: "var(--font-body)",
      }}>›</div>
    </div>
  );
}

function Token({ scale, children }) {
  return (
    <span style={{
      display: "inline-block",
      border: "1px solid #a87830",
      padding: `0 ${5*scale}px`,
      borderRadius: 2,
      letterSpacing: ".05em",
      color: "#c89858",
      fontFamily: "var(--font-key)",
      fontWeight: 700,
    }}>{children}</span>
  );
}

/* ============================================================
   Single key (top label + button)
   ============================================================ */
function CalcKey({ kc, scale, onPress }) {
  const [pressed, setPressed] = useStateCalc(false);

  const styleByTone = {
    cream: {
      background: pressed
        ? "linear-gradient(180deg,#d8c8a8,#c0b08c)"
        : "linear-gradient(180deg,#efe4cc 0%,#d8c8a8 100%)",
      color: "#1a130d",
      shadow: pressed
        ? "inset 0 2px 4px rgba(0,0,0,.45)"
        : "0 1px 0 #6a5a3c, 0 2px 3px rgba(0,0,0,.5), inset 0 1px 0 rgba(255,255,255,.4)",
      radius: 6 * scale,
    },
    dark: {
      background: pressed
        ? "linear-gradient(180deg,#1a1208,#100a04)"
        : "linear-gradient(180deg,#2a1f15 0%,#1f1610 100%)",
      color: "#efe4cc",
      shadow: pressed
        ? "inset 0 2px 4px rgba(0,0,0,.6)"
        : "0 1px 0 #000, 0 2px 4px rgba(0,0,0,.5), inset 0 1px 0 rgba(255,200,100,.05)",
      radius: 7 * scale,
    },
    yellow: {
      background: pressed
        ? "linear-gradient(180deg,#d8a830,#b88a20)"
        : "linear-gradient(180deg,#f0c040 0%,#d8a830 100%)",
      color: "#2a1f10",
      shadow: pressed
        ? "inset 0 2px 4px rgba(0,0,0,.5)"
        : "0 1px 0 #5a3c10, 0 2px 3px rgba(0,0,0,.5), inset 0 1px 0 rgba(255,255,255,.25)",
      radius: 7 * scale,
    },
  }[kc.tone];

  const topColor = kc.tone === "yellow" ? "#e8b840"
                 : (kc.top && /[A-E]'/.test(kc.top)) ? "#d4c4a0"
                 : "#d4c4a0";

  return (
    <div style={{ display:"flex", flexDirection:"column", alignItems:"center", gap: 2*scale }}>
      <span style={{
        fontFamily: kc.top && /[a-z]/.test(kc.top) ? "var(--font-body)" : "var(--font-key)",
        fontStyle: kc.top && /[a-z]/.test(kc.top) ? "italic" : "normal",
        fontWeight: 500,
        fontSize: 11 * scale,
        height: 14 * scale,
        letterSpacing: kc.top && /[a-z]/.test(kc.top) ? ".02em" : ".04em",
        color: topColor,
        lineHeight: 1,
      }}>{kc.top || "\u00A0"}</span>
      <button
        onMouseDown={() => setPressed(true)}
        onMouseUp={() => setPressed(false)}
        onMouseLeave={() => setPressed(false)}
        onTouchStart={() => setPressed(true)}
        onTouchEnd={() => setPressed(false)}
        onClick={() => onPress(kc.label)}
        style={{
          width: "100%",
          height: 36 * scale,
          background: styleByTone.background,
          color: styleByTone.color,
          border: 0,
          borderRadius: styleByTone.radius,
          fontFamily: "var(--font-key)",
          fontWeight: 700,
          fontSize: kc.label.length > 3 ? 14 * scale : 16 * scale,
          letterSpacing: ".04em",
          textTransform: "uppercase",
          boxShadow: styleByTone.shadow,
          cursor: "pointer",
          transform: pressed ? "translateY(1px)" : "none",
          padding: 0,
        }}>
        {kc.label}
      </button>
    </div>
  );
}

/* ============================================================
   Bottom iOS toolbar
   ============================================================ */
function BottomToolbar({ scale }) {
  const icoSize = 22 * scale;
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 14 * scale,
      paddingTop: 14 * scale, paddingBottom: 6 * scale,
      paddingLeft: 4 * scale, paddingRight: 4 * scale,
    }}>
      {/* undo */}
      <SymbolUndo size={icoSize} color="#ff9f0a" />
      {/* TI-59 picker */}
      <button style={{
        background: "transparent", border: 0,
        color: "#0a84ff",
        fontFamily: "-apple-system, system-ui, sans-serif",
        fontSize: 17 * scale, fontWeight: 600,
        display: "flex", alignItems: "center", gap: 4,
        padding: 0, cursor: "pointer",
      }}>
        TI-59 <SymbolChevrons size={icoSize * 0.7} color="#0a84ff" />
      </button>
      <div style={{ flex: 1 }}></div>
      <SymbolDownload size={icoSize} color="#8e8e93" />
      <SymbolPlus size={icoSize} color="#8e8e93" />
      <SymbolShare size={icoSize} color="#8e8e93" />
      <SymbolGear size={icoSize} color="#8e8e93" />
    </div>
  );
}

/* ============================================================
   Inline SF-Symbol-ish icons (no external deps)
   ============================================================ */
function _S({ size, color, d, sw = 1.6, fill = "none" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke={color}
         strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"
         style={{ flex: "0 0 auto" }}>
      <path d={d} />
    </svg>
  );
}
function SymbolUndo({ size, color }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 12 a 9 9 0 1 0 3-6.7" />
      <polyline points="3 4 3 9 8 9" />
    </svg>
  );
}
function SymbolChevrons({ size, color }) {
  return <_S size={size} color={color} sw={2.2} d="M8 9 L12 6 L16 9 M8 15 L12 18 L16 15" />;
}
function SymbolDownload({ size, color }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3.5" y="4" width="17" height="16" rx="3" />
      <path d="M12 9 V 16 M9 13 L 12 16 L 15 13" />
    </svg>
  );
}
function SymbolPlus({ size, color }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3.5" y="4" width="17" height="16" rx="3" />
      <path d="M8 12 H 16 M12 8 V 16" />
    </svg>
  );
}
function SymbolShare({ size, color }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3.5" y="4" width="17" height="16" rx="3" />
      <path d="M12 14 V 7 M9 10 L 12 7 L 15 10" />
    </svg>
  );
}
function SymbolGear({ size, color }) {
  // 8-tooth gearshape: rectangular teeth around a ring with a center hole.
  // Matches SF Symbols `gearshape` silhouette.
  const teeth = [];
  const tw = 2.0;   // tooth width
  const th = 2.4;   // tooth height (outside ring)
  const r  = 7.5;   // outer ring radius
  for (let i = 0; i < 8; i++) {
    const a = (i * 45) * Math.PI / 180;
    const cx = 12 + Math.cos(a) * (r + th / 2);
    const cy = 12 + Math.sin(a) * (r + th / 2);
    teeth.push(
      <rect key={i}
        x={cx - tw / 2} y={cy - th / 2}
        width={tw} height={th}
        transform={`rotate(${i * 45} ${cx} ${cy})`}
        fill={color} stroke="none" rx="0.4" />
    );
  }
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      {teeth}
      {/* outer ring */}
      <circle cx="12" cy="12" r="7" fill={color} />
      {/* inner hole */}
      <circle cx="12" cy="12" r="3.2" fill="#000" />
    </svg>
  );
}

function applyOp(a, b, op) {
  switch (op) { case "+": return a + b; case "-": return a - b; case "×": return a * b; case "÷": return a / b; default: return b; }
}
function formatLED(n) {
  if (!isFinite(n) || isNaN(n)) return "Error";
  const s = (Math.abs(n) < 1e-6 || Math.abs(n) >= 1e10)
    ? n.toExponential(6)
    : (Math.round(n * 1e8) / 1e8).toString();
  return s.includes(".") ? s : s + ".";
}

Object.assign(window, {
  Calculator, Display, CalcKey, BottomToolbar,
  SymbolUndo, SymbolChevrons, SymbolDownload, SymbolPlus, SymbolShare, SymbolGear,
});
