// ============================================================
// Farm Fresh — screens: Login, Weight modal, Ticket sheet, Tickets history
// ============================================================
const { useState: useStateS, useEffect: useEffectS, useRef: useRefS } = React;

// ---------- Email + password login (secure, multi-device) ----------
function LoginScreen({ onUnlock }) {
  const [email, setEmail] = useStateS("");
  const [pw, setPw] = useStateS("");
  const [err, setErr] = useStateS("");
  const [busy, setBusy] = useStateS(false);

  const submit = async (e) => {
    if (e) e.preventDefault();
    if (!email || !pw) { setErr("Enter your email and password."); return; }
    setBusy(true); setErr("");
    try {
      const user = await FF.signIn(email, pw);
      onUnlock(user);
    } catch (ex) {
      setErr(ex && ex.message ? ex.message : "Could not sign in.");
      setBusy(false);
    }
  };

  return (
    <div style={{ height:"100%", display:"flex", flexDirection:"column", alignItems:"center",
      justifyContent:"center", padding:"32px 30px", background:
      "radial-gradient(120% 70% at 50% 0%, var(--green-bg), var(--bg) 60%)" }}>
      <div style={{ fontSize:58, marginBottom:6 }}>🧺</div>
      <h1 style={{ margin:"0 0 1px", fontSize:34, fontWeight:800, letterSpacing:"-.02em", color:"var(--green-ink)" }}>Farm Fresh</h1>
      <p style={{ margin:"0 0 22px", fontSize:12.5, fontWeight:700, letterSpacing:".02em", color:"var(--ink-faint)" }}>
        by <span style={{ color:"var(--terra-ink)" }}>C-us.com</span></p>

      <form onSubmit={submit} style={{ width:"100%", maxWidth:320, display:"flex", flexDirection:"column", gap:12 }}>
        <div className="adm-field">
          <label>Email</label>
          <input className="adm-input" type="email" inputMode="email" autoComplete="username"
            value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" />
        </div>
        <div className="adm-field">
          <label>Password</label>
          <input className="adm-input" type="password" autoComplete="current-password"
            value={pw} onChange={(e) => setPw(e.target.value)} placeholder="••••••••" />
        </div>
        {err && <div style={{ fontSize:13, fontWeight:700, color:"var(--terra-ink)", lineHeight:1.4 }}>{err}</div>}
        <button type="submit" className="btn btn-green" disabled={busy} style={{ width:"100%", marginTop:4 }}>
          {busy ? "Signing in…" : "Sign in"}
        </button>
      </form>

      <p style={{ marginTop:22, fontSize:12, color:"var(--ink-faint)", fontWeight:600, textAlign:"center", lineHeight:1.5 }}>
        🔒 Secure login · works on any device
      </p>
    </div>
  );
}

// ---------- Weight entry modal ----------
function WeightModal({ item, initial, onConfirm, onCancel }) {
  const [val, setVal] = useStateS(initial != null ? String(initial) : "");
  const w = parseFloat(val || "0") || 0;
  const total = item.price * w;
  return (
    <div className="scrim center" onClick={onCancel}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()} style={{ padding:"22px 20px 20px" }}>
        <div style={{ display:"flex", alignItems:"center", gap:12, marginBottom:14 }}>
          <span style={{ fontSize:42 }}>{item.emoji}</span>
          <div style={{ flex:1 }}>
            <div style={{ fontWeight:800, fontSize:20 }}>{item.name}</div>
            <div className="mono" style={{ color:"var(--ink-soft)", fontSize:13 }}>{FF.money(item.price)} / lb</div>
          </div>
        </div>

        <div style={{ display:"flex", alignItems:"baseline", justifyContent:"space-between",
          background:"var(--surface)", border:"1.5px solid var(--line)", borderRadius:14,
          padding:"14px 16px", marginBottom:14 }}>
          <div>
            <div style={{ fontSize:11.5, fontWeight:700, color:"var(--ink-faint)", textTransform:"uppercase", letterSpacing:".05em" }}>Weight</div>
            <div className="mono" style={{ fontSize:30, fontWeight:700 }}>{val || "0"}<span style={{ fontSize:16, color:"var(--ink-faint)" }}> lb</span></div>
          </div>
          <div style={{ textAlign:"right" }}>
            <div style={{ fontSize:11.5, fontWeight:700, color:"var(--ink-faint)", textTransform:"uppercase", letterSpacing:".05em" }}>Line total</div>
            <div className="mono" style={{ fontSize:30, fontWeight:700, color:"var(--green-ink)" }}>{FF.money(total)}</div>
          </div>
        </div>

        <Keypad onKey={(k) => setVal(v => FF.applyKey(v, k, true))} allowDecimal={true} />

        <div style={{ display:"grid", gridTemplateColumns:"1fr 1.4fr", gap:10, marginTop:16 }}>
          <button className="btn btn-ghost" onClick={onCancel}>Cancel</button>
          <button className="btn btn-green" disabled={w <= 0} onClick={() => onConfirm(w)}>
            {initial != null ? "Update" : "Add to ticket"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------- Full ticket sheet (review / edit / complete) ----------
function TicketSheet({ ticket, catalog, onClose, onChangeLine, onRemoveLine, onEditWeight, onComplete, onClear, onPutBack, saving, number }) {
  const total = FF.ticketTotal(ticket, catalog);
  const lines = ticket.lines || [];
  const reopened = !!ticket.reopened;
  return (
    <div className="scrim" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()} style={{ minHeight:"56%" }}>
        <div className="grab" />
        <div className="sheet-head">
          <div>
            <h2>{reopened ? "Reopened Ticket" : "Current Ticket"}</h2>
            <div style={{ display:"flex", alignItems:"center", gap:9, marginTop:2 }}>
              <span className="mono" style={{ fontSize:12.5, fontWeight:700,
                color: reopened ? "var(--terra-ink)" : "var(--ink-faint)" }}>No. {number}</span>
              {reopened && (
                <button onClick={onPutBack}
                  style={{ fontSize:12, fontWeight:800, color:"var(--green-ink)", background:"var(--green-bg)",
                    padding:"4px 11px", borderRadius:999 }}>Put back ↩</button>
              )}
            </div>
          </div>
          <button className="x-btn" onClick={onClose}>✕</button>
        </div>

        <div className="scroll" style={{ padding:"0 16px", flex:1 }}>
          {lines.length === 0 && (
            <div style={{ textAlign:"center", padding:"50px 20px", color:"var(--ink-faint)" }}>
              <div style={{ fontSize:40, marginBottom:8 }}>🧺</div>
              <div style={{ fontWeight:700 }}>Ticket is empty</div>
              <div style={{ fontSize:13.5, marginTop:3 }}>Tap produce to add items.</div>
            </div>
          )}
          {lines.map((line, i) => {
            const item = catalog.find(c => c.id === line.itemId);
            if (!item) return null;
            const lt = FF.lineTotal(line, catalog);
            return (
              <div key={i} style={{ display:"flex", alignItems:"center", gap:11, padding:"11px 0",
                borderBottom:"1.5px solid var(--line-soft)" }}>
                <span style={{ fontSize:30 }}>{item.emoji}</span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontWeight:700, fontSize:15.5 }}>{item.name}</div>
                  <div className="mono" style={{ fontSize:12.5, color:"var(--ink-soft)" }}>
                    {item.unit === "lb"
                      ? <button onClick={() => onEditWeight(i)} style={{ color:"var(--terra-ink)", fontWeight:700, textDecoration:"underline" }}>{line.weight} lb</button>
                      : null} {item.unit === "lb" ? " × " : ""}{FF.money(item.price)}{item.unit === "lb" ? "" : " ea"}
                  </div>
                </div>
                {item.unit === "each"
                  ? <Stepper value={line.qty} min={0} onChange={(q) => q === 0 ? onRemoveLine(i) : onChangeLine(i, { qty:q })} />
                  : null}
                <div className="mono" style={{ width:64, textAlign:"right", fontWeight:700, fontSize:15.5 }}>{FF.money(lt)}</div>
                <button onClick={() => onRemoveLine(i)} style={{ color:"var(--ink-faint)", fontSize:18, width:26 }}>✕</button>
              </div>
            );
          })}
        </div>

        <div style={{ padding:"14px 18px 20px", borderTop:"1.5px solid var(--line)", flex:"none" }}>
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom:14 }}>
            <span style={{ fontWeight:800, fontSize:20 }}>Total</span>
            <span className="mono" style={{ fontWeight:700, fontSize:34, color:"var(--green-ink)" }}>{FF.money(total)}</span>
          </div>
          <div style={{ display:"flex", gap:10 }}>
            <button className="btn btn-ghost" disabled={lines.length === 0 || saving} onClick={onClear}
              style={{ flex:"none", padding:"16px 20px" }}>Clear</button>
            <button className="btn btn-terra" disabled={lines.length === 0 || saving} onClick={onComplete} style={{ flex:1, fontSize:18 }}>
              {saving ? "Saving…" : <span>✓&nbsp; Complete Sale</span>}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- Today's tickets history ----------
function TicketsSheet({ day, catalog, onClose, onReopen, onPutBack, onVoid }) {
  const tickets = [...(day.tickets || [])].reverse();
  const dayTotal = tickets.filter(t => !t.voided).reduce((s, t) => s + FF.ticketTotal(t, catalog), 0);
  return (
    <div className="scrim" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()} style={{ minHeight:"60%" }}>
        <div className="grab" />
        <div className="sheet-head">
          <div>
            <h2>Today's Sales</h2>
            <div className="mono" style={{ fontSize:12.5, color:"var(--ink-faint)", fontWeight:700 }}>{FF.prettyDate(day.date)}</div>
          </div>
          <button className="x-btn" onClick={onClose}>✕</button>
        </div>

        <div style={{ display:"flex", gap:10, padding:"0 18px 12px" }}>
          <div style={{ flex:1, background:"var(--green-bg)", borderRadius:14, padding:"12px 14px" }}>
            <div style={{ fontSize:11.5, fontWeight:700, color:"var(--green-ink)", textTransform:"uppercase", letterSpacing:".05em" }}>Day total</div>
            <div className="mono" style={{ fontSize:26, fontWeight:700, color:"var(--green-ink)" }}>{FF.money(dayTotal)}</div>
          </div>
          <div style={{ flex:1, background:"var(--surface)", border:"1.5px solid var(--line)", borderRadius:14, padding:"12px 14px" }}>
            <div style={{ fontSize:11.5, fontWeight:700, color:"var(--ink-faint)", textTransform:"uppercase", letterSpacing:".05em" }}>Tickets</div>
            <div className="mono" style={{ fontSize:26, fontWeight:700 }}>{tickets.length}</div>
          </div>
        </div>

        <div className="scroll" style={{ padding:"0 16px 20px", flex:1 }}>
          {tickets.length === 0 && (
            <div style={{ textAlign:"center", padding:"40px 20px", color:"var(--ink-faint)" }}>
              <div style={{ fontSize:38, marginBottom:8 }}>🧾</div>
              <div style={{ fontWeight:700 }}>No sales yet today</div>
            </div>
          )}
          {tickets.map((t) => {
            const tot = FF.ticketTotal(t, catalog);
            const count = (t.lines || []).length;

            // ---- voided sale: audit record, no actions ----
            if (t.voided) {
              return (
                <div key={t.number}
                  style={{ display:"flex", alignItems:"center", gap:12,
                    padding:"13px 14px", marginBottom:9, background:"var(--bg-2)",
                    border:"1.5px solid var(--line-soft)", borderRadius:14, opacity:.9 }}>
                  <div className="mono" style={{ width:46, height:46, borderRadius:11, background:"var(--surface)",
                    display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", flex:"none", border:"1.5px solid var(--line)" }}>
                    <span style={{ fontSize:9, color:"var(--ink-faint)", fontWeight:700 }}>NO.</span>
                    <span style={{ fontSize:15, fontWeight:700, color:"var(--ink-faint)" }}>{FF.pad3(t.number)}</span>
                  </div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                      <span className="mono" style={{ fontWeight:700, fontSize:17, color:"var(--ink-faint)", textDecoration:"line-through" }}>{FF.money(tot)}</span>
                      <span style={{ fontSize:11, fontWeight:800, color:"#fff", background:"var(--terra)", padding:"2px 8px", borderRadius:999, letterSpacing:".03em" }}>VOID</span>
                    </div>
                    <div style={{ fontSize:12, color:"var(--ink-soft)", fontWeight:600, marginTop:3, lineHeight:1.35 }}>
                      {t.voidReason || "Voided"}{t.voidedBy ? " · by " + t.voidedBy : ""}
                    </div>
                  </div>
                </div>
              );
            }

            // ---- normal sale ----
            return (
              <div key={t.number}
                style={{ display:"flex", alignItems:"center", gap:12,
                  padding:"13px 14px", marginBottom:9, background:"var(--surface)",
                  border:"1.5px solid var(--line)", borderRadius:14, boxShadow:"var(--shadow-card)" }}>
                <div className="mono" style={{ width:46, height:46, borderRadius:11, background:"var(--bg-2)",
                  display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", flex:"none" }}>
                  <span style={{ fontSize:9, color:"var(--ink-faint)", fontWeight:700 }}>NO.</span>
                  <span style={{ fontSize:15, fontWeight:700 }}>{FF.pad3(t.number)}</span>
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div className="mono" style={{ fontWeight:700, fontSize:18 }}>{FF.money(tot)}</div>
                  <div style={{ fontSize:12.5, color:"var(--ink-soft)", fontWeight:600 }}>
                    {FF.clock(t.time)} · {count} item{count !== 1 ? "s" : ""}
                    {t.reopened && (
                      <span style={{ marginLeft:7, fontSize:11, fontWeight:700, color:"var(--terra-ink)",
                        background:"var(--terra-bg)", padding:"1px 7px", borderRadius:999 }}>Reopened</span>
                    )}
                  </div>
                </div>
                <div style={{ display:"flex", flexDirection:"column", gap:6, flex:"none" }}>
                  <button onClick={() => onReopen(t.number)}
                    style={{ fontSize:12.5, fontWeight:700, color:"var(--terra-ink)",
                      background:"var(--terra-bg)", padding:"7px 12px", borderRadius:999 }}>Reopen ↺</button>
                  {t.reopened && (
                    <button onClick={() => onPutBack(t.number)}
                      style={{ fontSize:12.5, fontWeight:700, color:"var(--green-ink)",
                        background:"var(--green-bg)", padding:"7px 12px", borderRadius:999 }}>Put back ↩</button>
                  )}
                  <button onClick={() => onVoid(t.number, tot)}
                    style={{ fontSize:12.5, fontWeight:700, color:"var(--ink-soft)",
                      background:"var(--bg-2)", border:"1.5px solid var(--line)", padding:"6px 12px", borderRadius:999 }}>Void</button>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen, WeightModal, TicketSheet, TicketsSheet });
