// Approvals queue page + Voucher Detail Drawer (the receipt that gets approved)
// + Mobile operator UI

function ApprovalsPage({ highlightId, openDetailFor, isApproving, isApproved }) {
  const pendingCount = PENDING_APPROVALS.length - (isApproved ? 1 : 0);
  return (
    <main className="px-8 py-6 space-y-5">
      <BiPageHeader title="Approvals" subtitle={`${pendingCount} ${pendingCount === 1 ? "voucher" : "vouchers"} pending review`}/>
      <div className="grid grid-cols-[1fr_560px] gap-5 items-start">
      {/* Queue */}
      <Card className="overflow-hidden">
        <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--hairline)] gap-3">
          <div className="min-w-0">
            <h3 className="text-[14.5px] font-semibold text-[var(--ink)] whitespace-nowrap">Pending Vouchers</h3>
            <div className="text-[12px] text-[var(--ink-3)] mt-0.5 whitespace-nowrap">Awaiting manager review</div>
          </div>
          <div className="flex items-center gap-1 p-0.5 rounded-md bg-[var(--sunken)] flex-shrink-0">
            <button className="h-7 px-2.5 rounded text-[12px] font-medium bg-[var(--surface)] shadow-[var(--elev-1)] text-[var(--ink)] whitespace-nowrap">All</button>
            <button className="h-7 px-2.5 rounded text-[12px] font-medium text-[var(--ink-3)] whitespace-nowrap">Receipts</button>
            <button className="h-7 px-2.5 rounded text-[12px] font-medium text-[var(--ink-3)] whitespace-nowrap">Dispatches</button>
          </div>
        </div>
        <table className="w-full">
          <thead>
            <tr className="border-b border-[var(--hairline)] bg-[var(--canvas)]">
              <th className="type-table-head text-left px-5 py-2.5">Voucher</th>
              <th className="type-table-head text-left px-3 py-2.5">Type</th>
              <th className="type-table-head text-left px-3 py-2.5">By</th>
              <th className="type-table-head text-right px-3 py-2.5">Lines</th>
              <th className="type-table-head text-right px-5 py-2.5">Value</th>
            </tr>
          </thead>
          <tbody>
            {PENDING_APPROVALS.map((p) => {
              const isHighlighted = highlightId === p.id;
              const isOpen = openDetailFor === p.id;
              const isDone = isApproved && p.id === highlightId;
              return (
                <tr key={p.id}
                data-id={`approval-row-${p.id}`}
                className={cn(
                  "border-b border-[var(--hairline)] last:border-0 transition-all",
                  isOpen && "bg-[var(--accent-1-wash)]",
                  isHighlighted && !isOpen && "bg-[var(--accent-1-wash)]",
                  isDone && "opacity-50"
                )}>
                  <td className="px-5 py-3.5 whitespace-nowrap">
                    <div className="text-[13px] font-semibold text-[var(--ink)] mono whitespace-nowrap">{p.id}</div>
                    <div className="text-[11px] text-[var(--ink-3)] whitespace-nowrap">{p.party}</div>
                  </td>
                  <td className="px-3 py-3.5">
                    <Pill kind={p.type === "Receipt" ? "positive" : p.type === "Dispatch" ? "info" : "neutral"}>{p.type}</Pill>
                  </td>
                  <td className="px-3 py-3.5">
                    <div className="flex items-center gap-2 whitespace-nowrap">
                      <Avatar initials={p.by.split(" ").map((s) => s[0]).join("").slice(0, 2)} size={22} tint="oklch(0.86 0.06 200)" color="oklch(0.30 0.10 200)" className="flex-shrink-0" />
                      <span className="text-[12.5px] text-[var(--ink-2)] whitespace-nowrap">{p.by}</span>
                    </div>
                  </td>
                  <td className="px-3 py-3.5 text-right text-[13px] tabular-nums">{p.lines}</td>
                  <td className="px-5 py-3.5 text-right text-[13px] font-semibold tabular-nums">{fmtINR(p.value)}</td>
                </tr>);

            })}
          </tbody>
        </table>
      </Card>

      {/* Detail drawer */}
      {openDetailFor &&
      <VoucherDetail isApproving={isApproving} isApproved={isApproved} />
      }
      </div>
    </main>);

}

function VoucherDetail({ isApproving, isApproved }) {
  const voucher = PENDING_APPROVALS.find((p) => p.id === "GRN-2026-0184");
  const supplier = SUPPLIERS[0];
  return (
    <Card className="overflow-hidden" dataId="voucher-detail">
      {/* Header */}
      <div className="px-5 py-4 border-b border-[var(--hairline)]">
        <div className="flex items-start justify-between mb-3">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <span className="text-[12px] font-semibold text-[var(--ink-3)] uppercase tracking-wide">Goods Receipt Note</span>
              <Pill kind="caution"><Icon name="clock" size={10} />Pending Review</Pill>
              {isApproving && <Pill kind="accent"><Icon name="loader" size={10} />Approving…</Pill>}
              {isApproved && <Pill kind="positive"><Icon name="check" size={10} />Approved · Stock applied</Pill>}
            </div>
            <h3 className="text-[18px] font-semibold text-[var(--ink)] mono">GRN-2026-0184</h3>
            <div className="text-[12px] text-[var(--ink-3)] mt-1">Linked to <span className="mono text-[var(--accent-1-text)] font-semibold">PO-2026-0091</span> · 3 lines</div>
          </div>
          <div className="flex flex-col gap-1.5">
            <Button size="sm" variant="success" dataId="btn-approve">
              <Icon name="check" size={13} />Approve
            </Button>
            <Button size="sm" variant="ghost"><Icon name="x" size={13} />Reject</Button>
          </div>
        </div>

        <div className="grid grid-cols-3 gap-3 text-[12px]">
          <div>
            <div className="text-[10.5px] uppercase tracking-[0.06em] text-[var(--ink-3)] font-medium mb-0.5">Supplier</div>
            <div className="text-[12.5px] font-semibold text-[var(--ink)]">{supplier.name}</div>
            <div className="text-[11px] mono text-[var(--ink-3)]">{supplier.gstin}</div>
          </div>
          <div>
            <div className="text-[10.5px] uppercase tracking-[0.06em] text-[var(--ink-3)] font-medium mb-0.5">Receive At</div>
            <div className="text-[12.5px] font-semibold text-[var(--ink)]">MUM-1</div>
            <div className="text-[11px] text-[var(--ink-3)]">Mumbai Central Warehouse</div>
          </div>
          <div>
            <div className="text-[10.5px] uppercase tracking-[0.06em] text-[var(--ink-3)] font-medium mb-0.5">Submitted</div>
            <div className="text-[12.5px] font-semibold text-[var(--ink)]">Ravi Kumar</div>
            <div className="text-[11px] text-[var(--ink-3)]">07 May 2026, 09:17 AM · Telegram</div>
          </div>
        </div>
      </div>

      {/* Lines */}
      <div className="px-5 py-3 bg-[var(--canvas)] border-b border-[var(--hairline)]">
        <div className="text-[10.5px] uppercase tracking-[0.06em] text-[var(--ink-3)] font-medium">3 Line Items</div>
      </div>
      <table className="w-full">
        <thead>
          <tr className="border-b border-[var(--hairline)]">
            <th className="type-table-head text-left px-5 py-2">Item</th>
            <th className="type-table-head text-right px-3 py-2">Qty</th>
            <th className="type-table-head text-right px-3 py-2">Rate</th>
            <th className="type-table-head text-right px-5 py-2">Amount</th>
          </tr>
        </thead>
        <tbody>
          {RECEIPT_LINES.map((l) => {
            const it = itemById(l.itemId);
            return (
              <tr key={l.itemId} className="border-b border-[var(--hairline)] last:border-0">
                <td className="px-5 py-3">
                  <div className="text-[13px] font-semibold text-[var(--ink)]">{it.name}</div>
                  <div className="text-[11px] text-[var(--ink-3)] mono">{it.sku}</div>
                </td>
                <td className="px-3 py-3 text-right">
                  <div className="text-[13.5px] font-semibold tabular-nums">{l.qty}</div>
                  <div className="text-[11px] text-[var(--ink-3)]">{l.unit}</div>
                </td>
                <td className="px-3 py-3 text-right text-[13px] tabular-nums text-[var(--ink-2)]">{fmtINR(l.rate)}</td>
                <td className="px-5 py-3 text-right text-[13px] font-semibold tabular-nums">{fmtINR(l.qty * l.rate)}</td>
              </tr>);

          })}
        </tbody>
      </table>

      <div className="px-5 py-3 border-t border-[var(--hairline)] bg-[var(--canvas)]">
        <div className="flex items-center justify-between">
          <div className="text-[11.5px] text-[var(--ink-3)]">3 lines · 660 units total</div>
          <div className="text-[15px] font-semibold tabular-nums text-[var(--ink)]">{fmtINR(RECEIPT_LINES.reduce((s, l) => s + l.qty * l.rate, 0))}</div>
        </div>
      </div>

      {/* Stock impact preview */}
      <div className="px-5 py-4 border-t border-[var(--hairline)] bg-[var(--accent-1-wash)]">
        <div className="flex items-center gap-2 mb-3">
          <Icon name="zap" size={13} className="text-[var(--accent-1-text)]" />
          <div className="text-[12px] font-semibold text-[var(--accent-1-text)]">On approval, stock at MUM-1 will update</div>
        </div>
        <div className="space-y-2">
          {RECEIPT_LINES.map((l) => {
            const it = itemById(l.itemId);
            const before = STOCK_BEFORE.find((r) => r.itemId === l.itemId && r.locId === "loc-mum-1")?.qty ?? 0;
            const after = before + l.qty;
            return (
              <div key={l.itemId} className="flex items-center gap-3 text-[12.5px]">
                <span className="flex-1 text-[var(--ink-2)]">{it.name}</span>
                <span className="tabular-nums text-[var(--ink-3)]">{before}</span>
                <Icon name="arrow-right" size={11} className="text-[var(--ink-4)]" />
                <span className="tabular-nums font-semibold text-[var(--positive-text)]">{after}</span>
                <span className="text-[11px] text-[var(--positive-text)] font-medium tabular-nums">+{l.qty}</span>
              </div>);

          })}
        </div>
      </div>
    </Card>);

}

// Mobile operator UI — phone frame to the right of mobile-shaped scenes
function MobileOperator({ scene = "list" }) {
  return (
    <main className="px-12 py-10 grid grid-cols-[minmax(0,1fr)_400px] gap-16 items-center" data-comment-anchor="5b22cc5f2b-main-190-5" style={{minHeight: "calc(100vh - 120px)"}}>
      {/* Left: marketing-ish explainer */}
      <div className="max-w-[640px]">
        <Pill kind="info" className="mb-5 whitespace-nowrap"><Icon name="smartphone" size={11} />Operator on Mobile</Pill>
        <h2 className="text-[34px] font-semibold leading-[1.1]" style={{ fontFamily: "var(--font-display)", letterSpacing: "-0.02em", textWrap: "balance" }}>
          Field operators submit receipts from the warehouse floor.
        </h2>
        <p className="text-[15px] text-[var(--ink-2)] mt-5 leading-relaxed" style={{textWrap: "pretty"}}>
          Ravi unloads the Britannia delivery. He opens the Telegram Mini App,
          scans the supplier’s invoice, confirms the lines, and submits.
          The voucher lands in Priya’s queue with status <span className="mono text-[var(--accent-1-text)] font-semibold whitespace-nowrap">pending_review</span>.
        </p>

        <div className="mt-8 flex flex-col gap-5">
          {[
          { icon: "scan-line", title: "Scan supplier invoice", note: "OCR via Gemini auto-fills items, qty, rate" },
          { icon: "check-check", title: "Operator can never apply stock", note: "Submission is always pending_review" },
          { icon: "shield-check", title: "Manager sees a full evidence trail", note: "Photos, OCR confidence, GPS — attached" }].
          map((s, i) =>
          <div key={i} className="flex items-start gap-4">
              <div className="w-10 h-10 rounded-md grid place-items-center flex-shrink-0" style={{ background: "var(--accent-1-tint)", color: "var(--accent-1-text)" }}>
                <Icon name={s.icon} size={17} />
              </div>
              <div className="min-w-0 pt-0.5 flex-1">
                <div className="text-[14px] font-semibold text-[var(--ink)] leading-snug whitespace-nowrap">{s.title}</div>
                <div className="text-[12.5px] text-[var(--ink-3)] mt-1 leading-relaxed">{s.note}</div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Right: phone */}
      <div className="flex justify-center">
        <PhoneFrame>
          {scene === "list" && <MobileListScene />}
          {scene === "review" && <MobileReviewScene />}
          {scene === "submitted" && <MobileSubmittedScene />}
        </PhoneFrame>
      </div>
    </main>);

}

function PhoneFrame({ children }) {
  return (
    <div style={{
      width: 360, height: 740,
      borderRadius: 44, padding: 10,
      background: "linear-gradient(160deg, oklch(0.22 0.01 260), oklch(0.10 0.01 260))",
      boxShadow: "0 40px 80px -20px oklch(0.16 0.01 260 / 0.35), 0 0 0 1px oklch(0.16 0.01 260 / 0.4)"
    }}>
      <div style={{
        width: "100%", height: "100%", borderRadius: 36, overflow: "hidden",
        background: "var(--paper)", position: "relative"
      }}>
        {/* notch */}
        <div style={{ position: "absolute", top: 8, left: "50%", transform: "translateX(-50%)", width: 110, height: 28, background: "oklch(0.10 0.01 260)", borderRadius: 18, zIndex: 30 }} />
        {/* status bar */}
        <div style={{ height: 44, padding: "0 22px" }} className="flex items-center justify-between text-[12px] font-semibold text-[var(--ink)] relative z-20">
          <span>09:17</span>
          <div className="flex items-center gap-1">
            <Icon name="signal" size={12} />
            <Icon name="wifi" size={12} />
            <Icon name="battery-full" size={14} />
          </div>
        </div>
        {children}
      </div>
    </div>);

}

function MobileChrome({ title, subtitle, children, accent = false }) {
  return (
    <>
      <div style={{ padding: "8px 16px 12px", borderBottom: "1px solid var(--hairline)", background: accent ? "var(--accent-1-tint)" : "var(--surface)" }}
      className="flex items-center gap-3">
        <button className="w-8 h-8 rounded-full grid place-items-center bg-[var(--surface)] border border-[var(--hairline)]"><Icon name="chevron-left" size={14} /></button>
        <div className="flex-1">
          <div className="text-[14px] font-semibold text-[var(--ink)] leading-tight">{title}</div>
          {subtitle && <div className="text-[11px] text-[var(--ink-3)]">{subtitle}</div>}
        </div>
        <Icon name="more-horizontal" size={16} className="text-[var(--ink-3)]" />
      </div>
      <div style={{ height: "calc(100% - 44px - 53px)", overflow: "auto" }} className="px-4 py-3 space-y-3">
        {children}
      </div>
    </>);

}

function MobileListScene() {
  return (
    <MobileChrome title="Inward" subtitle="Pending submissions">
      <button data-id="mob-create" className="w-full h-12 rounded-xl flex items-center gap-2.5 px-4 text-[14px] font-semibold text-white whitespace-nowrap"
      style={{ background: "linear-gradient(135deg, var(--accent-1) 0%, oklch(0.42 0.21 268) 100%)" }}>
        <Icon name="plus" size={16} />New Receipt
        <span className="ml-auto opacity-80 text-[11px] font-normal whitespace-nowrap">Scan invoice</span>
      </button>
      <div className="text-[10.5px] uppercase tracking-[0.06em] text-[var(--ink-3)] font-medium mt-4 mb-2 px-1">Today</div>
      {[
      { id: "GRN-2026-0182", party: "ITC Foods", at: "08:14", status: "open", lines: 5 },
      { id: "GRN-2026-0181", party: "Mahesh Wholesale", at: "07:42", status: "open", lines: 2 }].
      map((r) =>
      <div key={r.id} className="rounded-xl border border-[var(--hairline)] bg-[var(--surface)] p-3.5">
          <div className="flex items-center justify-between gap-2 mb-1">
            <span className="text-[12px] mono font-semibold text-[var(--ink)] whitespace-nowrap truncate">{r.id}</span>
            <StatusBadge status={r.status} label="Approved" />
          </div>
          <div className="text-[12px] text-[var(--ink-2)] truncate">{r.party}</div>
          <div className="text-[11px] text-[var(--ink-3)] mt-1.5 whitespace-nowrap">{r.lines} lines · {r.at}</div>
        </div>
      )}
    </MobileChrome>);

}

function MobileReviewScene() {
  return (
    <MobileChrome title="GRN-2026-0184" subtitle="Britannia Industries · MUM-1" accent>
      {/* Scanned invoice preview */}
      <div className="rounded-xl overflow-hidden border border-[var(--hairline)] bg-[var(--canvas)] p-3 flex items-center gap-3">
        <div style={{ width: 56, height: 70, background: "var(--surface)", border: "1px solid var(--hairline)", borderRadius: 6, position: "relative" }} className="overflow-hidden">
          <div style={{ position: "absolute", top: 6, left: 6, right: 6, height: 4, background: "oklch(0.86 0.005 260)", borderRadius: 2 }} />
          <div style={{ position: "absolute", top: 14, left: 6, right: 18, height: 3, background: "oklch(0.90 0.005 260)", borderRadius: 2 }} />
          <div style={{ position: "absolute", top: 22, left: 6, right: 10, height: 3, background: "oklch(0.90 0.005 260)", borderRadius: 2 }} />
          <div style={{ position: "absolute", top: 30, left: 6, right: 14, height: 3, background: "oklch(0.90 0.005 260)", borderRadius: 2 }} />
          <div style={{ position: "absolute", top: 38, left: 6, right: 6, height: 2, background: "oklch(0.92 0.005 260)" }} />
          <div style={{ position: "absolute", top: 44, left: 6, right: 8, height: 2, background: "oklch(0.92 0.005 260)" }} />
          <div style={{ position: "absolute", top: 50, left: 6, right: 18, height: 2, background: "oklch(0.92 0.005 260)" }} />
          <div style={{ position: "absolute", bottom: 4, left: 6, right: 14, height: 4, background: "var(--accent-1)", opacity: 0.7, borderRadius: 1 }} />
        </div>
        <div className="flex-1">
          <div className="text-[12px] font-semibold text-[var(--ink)]">Supplier invoice</div>
          <div className="text-[11px] text-[var(--ink-3)]">INV-BR-25/4521 · 07 May</div>
          <div className="flex items-center gap-1 text-[10.5px] text-[var(--positive-text)] mt-1">
            <Icon name="sparkles" size={10} />OCR · 96% confidence
          </div>
        </div>
      </div>

      <div className="text-[10.5px] uppercase tracking-[0.06em] text-[var(--ink-3)] font-medium mt-2 px-1">3 Lines · auto-extracted</div>
      {RECEIPT_LINES.map((l) => {
        const it = itemById(l.itemId);
        return (
          <div key={l.itemId} className="rounded-xl border border-[var(--hairline)] bg-[var(--surface)] p-3.5">
            <div className="text-[12.5px] font-semibold text-[var(--ink)] leading-tight">{it.name}</div>
            <div className="text-[10.5px] mono text-[var(--ink-3)]">{it.sku}</div>
            <div className="flex items-end justify-between mt-2">
              <div>
                <div className="text-[10px] uppercase tracking-[0.06em] text-[var(--ink-3)] font-medium">Qty</div>
                <div className="text-[15px] font-semibold tabular-nums">{l.qty} <span className="text-[11px] text-[var(--ink-3)] font-normal">{l.unit.split(" ")[0]}</span></div>
              </div>
              <div className="text-right">
                <div className="text-[10px] uppercase tracking-[0.06em] text-[var(--ink-3)] font-medium">Rate</div>
                <div className="text-[14px] font-semibold tabular-nums">{fmtINR(l.rate)}</div>
              </div>
            </div>
          </div>);

      })}

      <div className="rounded-xl bg-[var(--canvas)] p-3.5 flex items-center justify-between mt-2">
        <span className="text-[12px] text-[var(--ink-3)]">Total value</span>
        <span className="text-[16px] font-semibold tabular-nums">{fmtINR(RECEIPT_LINES.reduce((s, l) => s + l.qty * l.rate, 0))}</span>
      </div>

      <button data-id="mob-submit" className="w-full h-12 rounded-xl flex items-center justify-center gap-2 text-[14px] font-semibold text-white mt-2"
      style={{ background: "var(--accent-1)" }}>
        <Icon name="send" size={14} />Submit for Approval
      </button>
      <div className="text-[10.5px] text-[var(--ink-3)] text-center px-3">Voucher will be created as <span className="mono font-semibold">pending_review</span> until your manager approves.</div>
    </MobileChrome>);

}

function MobileSubmittedScene() {
  return (
    <MobileChrome title="Submitted" subtitle="GRN-2026-0184">
      <div className="flex flex-col items-center text-center pt-6 px-3">
        <div style={{
          width: 72, height: 72, borderRadius: "50%",
          background: "var(--positive-tint)", color: "var(--positive-text)",
          display: "grid", placeItems: "center",
          animation: "pulse 1.6s ease-in-out infinite"
        }}>
          <Icon name="check" size={32} strokeWidth={2.5} />
        </div>
        <h3 className="text-[16px] font-semibold text-[var(--ink)] mt-4">Sent for approval</h3>
        <p className="text-[12.5px] text-[var(--ink-3)] mt-1.5 max-w-[260px]">
          Priya will be notified. You’ll see the voucher status update here when it’s approved.
        </p>
        <div className="mt-5 w-full rounded-xl border border-[var(--hairline)] bg-[var(--surface)] p-3.5 flex items-center gap-3">
          <div className="w-8 h-8 rounded-full bg-[var(--caution-tint)] grid place-items-center"><Icon name="clock" size={14} className="text-[var(--caution-text)]" /></div>
          <div className="flex-1 text-left">
            <div className="text-[12.5px] font-semibold text-[var(--ink)]">pending_review</div>
            <div className="text-[11px] text-[var(--ink-3)]">3 lines · {fmtINR(GRN_184_VALUE)} · MUM-1</div>
          </div>
        </div>
      </div>
    </MobileChrome>);

}

Object.assign(window, { ApprovalsPage, VoucherDetail, MobileOperator, PhoneFrame });