/* Willow Creek Portal — Resident experience: dashboard, payments, forms & signing. */
const { PIcon: RIcon, SignaturePad: RSignaturePad, PSection: RSection, KindBadge: RKindBadge, makeReceiptNo: rMakeReceiptNo, ReceiptModal: RReceiptModal } = window.WCPortal;
const { useState: rUseState } = React;

function ResidentPortal({ store, setStore, user, onLogout }) {
  const { Card, Button, Badge, Alert, Input, Textarea, ProgressBar, Tabs } = window.WillowCreekDesignSystem_90378c;
  const [tab, setTab] = rUseState("home");
  const [activeForm, setActiveForm] = rUseState(null);
  const [payOpen, setPayOpen] = rUseState(false);
  const [receipt, setReceipt] = rUseState(null);

  const resident = store.residents.find((r) => r.name === user) || store.residents[0];
  const signed = store.signedForms[resident.name] || [];
  const published = store.forms.filter((f) => f.status === "published");
  const pendingForms = published.filter((f) => !signed.includes(f.id));
  const myPayments = store.payments.filter((p) => p.resident === resident.name);
  const rate = store.cms.weeklyRate;

  const markSigned = (formId) => {
    setStore((s) => {
      const next = { ...s, signedForms: { ...s.signedForms, [resident.name]: [ ...(s.signedForms[resident.name] || []), formId ] } };
      return next;
    });
    setActiveForm(null);
  };
  const recordPayment = (amount) => {
    const paid = { id: "p" + Date.now(), resident: resident.name, amount, method: "Visa ··4242", status: "Paid", receiptNo: rMakeReceiptNo(),
      date: new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) };
    setStore((s) => ({
      ...s,
      payments: [paid, ...s.payments],
      residents: s.residents.map((r) => r.name === resident.name ? { ...r, balance: Math.max(0, r.balance - amount) } : r),
    }));
    setPayOpen(false);
    setReceipt(paid);
  };

  const navItems = [["home", "layout-dashboard", "Overview"], ["payments", "credit-card", "Payments"], ["forms", "file-signature", "Forms & waivers"]];

  return (
    <div style={{ display: "flex", minHeight: "100vh", background: "var(--surface-sunken)" }} className="wcp-shell">
      {/* Sidebar */}
      <aside style={{ width: 250, flexShrink: 0, background: "var(--surface-inverse)", color: "var(--sage-200)",
        display: "flex", flexDirection: "column", padding: "22px 16px" }} className="wcp-sidebar">
        <img src="../assets/logo-wordmark-inverse.svg" alt="Willow Creek" style={{ height: 38, alignSelf: "flex-start", marginBottom: 30 }} />
        <nav style={{ display: "flex", flexDirection: "column", gap: 4 }}>
          {navItems.map(([id, icon, label]) => (
            <button key={id} onClick={() => setTab(id)} style={{
              display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", borderRadius: "var(--radius-md)",
              background: tab === id ? "rgba(255,255,255,.1)" : "transparent", border: "none", cursor: "pointer",
              color: tab === id ? "#fffdf8" : "var(--sage-300)", fontFamily: "var(--font-sans)", fontWeight: 600,
              fontSize: "var(--text-sm)", textAlign: "left", transition: "all var(--dur-fast) var(--ease-out)",
            }}>
              <RIcon name={icon} size={18} /> {label}
              {id === "forms" && pendingForms.length > 0 && (
                <span style={{ marginLeft: "auto", background: "var(--clay-500)", color: "#fffdf8", borderRadius: 999,
                  fontSize: 11, fontWeight: 700, padding: "2px 8px" }}>{pendingForms.length}</span>
              )}
            </button>
          ))}
        </nav>
        <div style={{ marginTop: "auto", paddingTop: 20, borderTop: "1px solid rgba(255,255,255,.1)" }}>
          <div style={{ fontSize: "var(--text-sm)", fontWeight: 700, color: "#fffdf8" }}>{resident.name}</div>
          <div style={{ fontSize: 12, color: "var(--sage-300)", margin: "2px 0 12px" }}>{resident.house} · Phase {resident.phase}</div>
          <Button variant="ghost" size="sm" onClick={onLogout} style={{ color: "var(--sage-200)" }}
            leftIcon={<RIcon name="log-out" size={15} />}>Sign out</Button>
        </div>
      </aside>

      {/* Main */}
      <main style={{ flex: 1, padding: "34px clamp(20px, 4vw, 48px)", maxWidth: 1060 }}>
        {tab === "home" && (
          <>
            <h2 style={{ fontSize: "var(--text-d3)", margin: "0 0 4px" }}>Welcome back, {resident.name.split(" ")[0]}.</h2>
            <p style={{ color: "var(--text-muted)", margin: "0 0 26px" }}>One honest day at a time. Here's where things stand.</p>
            {resident.balance > 0 && (
              <Alert variant="warning" title={`$${resident.balance} due this week`} icon={<RIcon name="credit-card" size={20} />} style={{ marginBottom: 20 }}>
                Your weekly rate is ${rate}. <a href="#" onClick={(e) => { e.preventDefault(); setTab("payments"); setPayOpen(true); }}>Pay now</a> to stay current.
              </Alert>
            )}
            {pendingForms.length > 0 && (
              <Alert variant="info" title={`${pendingForms.length} form${pendingForms.length > 1 ? "s" : ""} need your signature`} icon={<RIcon name="file-signature" size={20} />} style={{ marginBottom: 20 }}>
                <a href="#" onClick={(e) => { e.preventDefault(); setTab("forms"); }}>Review and sign</a> — they only take a few minutes.
              </Alert>
            )}
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }} className="wcp-cards">
              <Card elevation="sm" padding="md">
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8, color: "var(--brand-primary)" }}>
                  <RIcon name="bed" size={20} /><strong style={{ color: "var(--text-heading)" }}>My bed</strong></div>
                <div style={{ color: "var(--text-body)", fontSize: "var(--text-sm)" }}>
                  {(store.houses.flatMap((h) => h.beds.map((b) => ({ ...b, house: h.name }))).find((b) => b.resident === resident.name) || {}).label || "—"}<br />
                  <span style={{ color: "var(--text-muted)" }}>{resident.house}</span>
                </div>
              </Card>
              <Card elevation="sm" padding="md">
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8, color: "var(--brand-accent)" }}>
                  <RIcon name="route" size={20} /><strong style={{ color: "var(--text-heading)" }}>Program phase</strong></div>
                <ProgressBar value={resident.phase} max={3} label={`Phase ${resident.phase} of 3`} variant="clay" />
              </Card>
              <Card elevation="sm" padding="md">
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8, color: "var(--brand-water)" }}>
                  <RIcon name="file-check-2" size={20} /><strong style={{ color: "var(--text-heading)" }}>Paperwork</strong></div>
                <ProgressBar value={signed.length} max={published.length} label={`${signed.length} of ${published.length} signed`} variant="water" />
              </Card>
            </div>
          </>
        )}

        {tab === "payments" && (
          <>
            <h2 style={{ fontSize: "var(--text-d3)", margin: "0 0 4px" }}>Payments</h2>
            <p style={{ color: "var(--text-muted)", margin: "0 0 26px" }}>One transparent weekly rate: ${rate}/week. No surprises.</p>
            <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 20, alignItems: "start" }} className="wcp-two">
              <Card elevation="sm" padding="lg">
                <RSection title="History" style={{ marginBottom: 0 }}>
                  <div>
                    {myPayments.length === 0 && <p style={{ color: "var(--text-muted)" }}>No payments yet.</p>}
                    {myPayments.map((p) => (
                      <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 0", borderBottom: "1px solid var(--border-subtle)" }}>
                        <span style={{ width: 38, height: 38, borderRadius: "var(--radius-sm)", background: "var(--surface-accent-soft)",
                          color: "var(--brand-primary)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                          <RIcon name="receipt" size={18} /></span>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontWeight: 600, color: "var(--text-heading)", fontSize: "var(--text-sm)" }}>Weekly program fee</div>
                          <div style={{ fontSize: 12, color: "var(--text-muted)" }}>{p.date} · {p.method} · {p.receiptNo}</div>
                        </div>
                        <strong style={{ color: "var(--text-heading)" }}>${p.amount}</strong>
                        <Badge variant="success" size="sm">{p.status}</Badge>
                        <Button variant="ghost" size="sm" onClick={() => setReceipt(p)}
                          leftIcon={<RIcon name="receipt-text" size={14} />}>Receipt</Button>
                      </div>
                    ))}
                  </div>
                </RSection>
              </Card>
              <Card elevation="md" padding="lg" style={{ position: "sticky", top: 20 }}>
                <div style={{ fontSize: "var(--text-sm)", color: "var(--text-muted)", marginBottom: 4 }}>Balance due</div>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 44, color: resident.balance > 0 ? "var(--clay-600)" : "var(--brand-primary)", lineHeight: 1 }}>
                  ${resident.balance}
                </div>
                <p style={{ fontSize: "var(--text-sm)", color: "var(--text-muted)", margin: "10px 0 18px" }}>
                  {resident.balance > 0 ? "Covers this week's program fee." : "You're all caught up. Nice."}
                </p>
                {!payOpen ? (
                  <Button variant="primary" fullWidth disabled={resident.balance === 0} onClick={() => setPayOpen(true)}
                    leftIcon={<RIcon name="credit-card" size={18} />}>Pay ${resident.balance || rate} securely</Button>
                ) : (
                  <StripeCheckout amount={resident.balance || rate} name={resident.name} onCancel={() => setPayOpen(false)} onPay={recordPayment} />
                )}
                <p style={{ display: "flex", alignItems: "center", gap: 6, justifyContent: "center", fontSize: 12, color: "var(--text-muted)", marginTop: 12 }}>
                  <RIcon name="lock" size={13} /> Secured by <strong style={{ color: "#635bff" }}>Stripe</strong> — demo mode, no real charge.
                </p>
              </Card>
            </div>
          </>
        )}

        {tab === "forms" && !activeForm && (
          <>
            <h2 style={{ fontSize: "var(--text-d3)", margin: "0 0 4px" }}>Forms & waivers</h2>
            <p style={{ color: "var(--text-muted)", margin: "0 0 26px" }}>Read carefully, fill in your details, and sign. Ask a house manager anything, any time.</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {published.map((f) => {
                const done = signed.includes(f.id);
                return (
                  <Card key={f.id} elevation="sm" padding="md" style={{ display: "flex", alignItems: "center", gap: 16 }}>
                    <span style={{ width: 44, height: 44, borderRadius: "var(--radius-md)", flexShrink: 0,
                      background: done ? "var(--success-soft)" : "var(--surface-clay-soft)",
                      color: done ? "var(--success)" : "var(--clay-600)",
                      display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                      <RIcon name={done ? "check" : "pen-line"} size={20} /></span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                        <strong style={{ color: "var(--text-heading)" }}>{f.title}</strong>
                        <RKindBadge kind={f.kind} />
                        {f.required && !done && <Badge variant="warning" size="sm">Required</Badge>}
                      </div>
                      <div style={{ fontSize: "var(--text-sm)", color: "var(--text-muted)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{f.body}</div>
                    </div>
                    {done
                      ? <Badge variant="success" dot>Signed</Badge>
                      : <Button variant="primary" size="sm" onClick={() => setActiveForm(f)}>Review & sign</Button>}
                  </Card>
                );
              })}
            </div>
          </>
        )}

        {tab === "forms" && activeForm && (
          <FormSigner form={activeForm} residentName={resident.name}
            onBack={() => setActiveForm(null)} onSigned={() => markSigned(activeForm.id)} />
        )}
      </main>
      {receipt && <RReceiptModal payment={receipt} cms={store.cms} onClose={() => setReceipt(null)} />}
    </div>
  );
}

/* Stripe-style embedded checkout (demo). */
function StripeCheckout({ amount, name, onCancel, onPay }) {
  const { Button } = window.WillowCreekDesignSystem_90378c;
  const [busy, setBusy] = rUseState(false);
  const [card, setCard] = rUseState("");
  const [exp, setExp] = rUseState("");
  const [cvc, setCvc] = rUseState("");
  const fmtCard = (v) => v.replace(/\D/g, "").slice(0, 16).replace(/(.{4})/g, "$1 ").trim();
  const fmtExp = (v) => {
    const d = v.replace(/\D/g, "").slice(0, 4);
    return d.length > 2 ? d.slice(0, 2) + " / " + d.slice(2) : d;
  };
  const submit = () => { setBusy(true); setTimeout(() => { setBusy(false); onPay(amount); }, 1100); };
  const fieldStyle = { width: "100%", border: "none", outline: "none", fontFamily: "var(--font-sans)",
    fontSize: 15, color: "var(--text-heading)", background: "transparent", padding: "12px 14px" };
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <span style={{ fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--text-heading)" }}>Card payment</span>
        <span aria-label="Stripe" style={{ fontFamily: "var(--font-sans)", fontWeight: 800, fontStyle: "italic",
          fontSize: 16, color: "#635bff", letterSpacing: "-0.02em" }}>stripe</span>
      </div>
      <div style={{ border: "1.5px solid var(--border-default)", borderRadius: "var(--radius-md)",
        background: "var(--surface-raised)", boxShadow: "var(--shadow-xs)", marginBottom: 12 }}>
        <div style={{ display: "flex", alignItems: "center", borderBottom: "1px solid var(--border-subtle)" }}>
          <RIcon name="credit-card" size={17} color="var(--text-subtle)" style={{ marginLeft: 14 }} />
          <input value={card} onChange={(e) => setCard(fmtCard(e.target.value))} placeholder="1234 1234 1234 1234"
            inputMode="numeric" autoComplete="cc-number" style={fieldStyle} />
        </div>
        <div style={{ display: "flex" }}>
          <input value={exp} onChange={(e) => setExp(fmtExp(e.target.value))} placeholder="MM / YY"
            inputMode="numeric" autoComplete="cc-exp" style={{ ...fieldStyle, borderRight: "1px solid var(--border-subtle)" }} />
          <input value={cvc} onChange={(e) => setCvc(e.target.value.replace(/\D/g, "").slice(0, 4))} placeholder="CVC"
            inputMode="numeric" autoComplete="cc-csc" style={fieldStyle} />
        </div>
      </div>
      <input defaultValue={name} placeholder="Name on card" style={{ width: "100%", boxSizing: "border-box",
        border: "1.5px solid var(--border-default)", borderRadius: "var(--radius-md)", fontFamily: "var(--font-sans)",
        fontSize: 15, color: "var(--text-heading)", padding: "12px 14px", marginBottom: 14, background: "var(--surface-raised)" }} />
      <button onClick={submit} disabled={busy} style={{ width: "100%", padding: "13px 16px", borderRadius: "var(--radius-md)",
        border: "none", cursor: busy ? "wait" : "pointer", background: "#635bff", color: "#fff",
        fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 15,
        boxShadow: "0 10px 22px -10px rgba(99,91,255,.55)", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
        {busy ? (
          <span style={{ width: 15, height: 15, borderRadius: "50%", border: "2px solid rgba(255,255,255,.5)",
            borderTopColor: "#fff", display: "inline-block", animation: "wc-spin .7s linear infinite" }} />
        ) : <RIcon name="lock" size={15} color="#fff" />}
        {busy ? "Processing…" : `Pay $${amount}.00`}
      </button>
      <button onClick={onCancel} style={{ width: "100%", marginTop: 8, padding: "9px", background: "none", border: "none",
        cursor: "pointer", color: "var(--text-muted)", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 13 }}>Cancel</button>
      <style>{"@keyframes wc-spin{to{transform:rotate(360deg)}}"}</style>
    </div>
  );
}

function FormSigner({ form, residentName, onBack, onSigned }) {
  const { Card, Button, Input, Textarea, Checkbox, Alert } = window.WillowCreekDesignSystem_90378c;
  const [agreed, setAgreed] = rUseState(false);
  const [hasSig, setHasSig] = rUseState(false);
  const [values, setValues] = rUseState({});
  const canSign = agreed && hasSig;
  return (
    <div style={{ maxWidth: 720 }}>
      <button onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "none", border: "none",
        cursor: "pointer", color: "var(--text-link)", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: "var(--text-sm)", padding: 0, marginBottom: 16 }}>
        <RIcon name="arrow-left" size={16} /> All forms
      </button>
      <Card elevation="lg" padding="xl">
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6, flexWrap: "wrap" }}>
          <RKindBadge kind={form.kind} />
          {form.required && <span style={{ fontSize: 12, color: "var(--clay-600)", fontWeight: 700 }}>REQUIRED</span>}
        </div>
        <h2 style={{ fontSize: "var(--text-d3)", margin: "0 0 16px" }}>{form.title}</h2>
        <div style={{ background: "var(--surface-sunken)", borderRadius: "var(--radius-md)", padding: "18px 20px",
          color: "var(--text-body)", lineHeight: 1.7, fontSize: "var(--text-md)", marginBottom: 22 }}>
          {form.body}
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 16, marginBottom: 22 }}>
          {form.fields.map((fl, i) => fl.type === "textarea"
            ? <Textarea key={i} label={fl.label} rows={3} value={values[i] || ""} onChange={(e) => setValues((v) => ({ ...v, [i]: e.target.value }))} />
            : <Input key={i} label={fl.label} type={fl.type} value={values[i] || ""} onChange={(e) => setValues((v) => ({ ...v, [i]: e.target.value }))} />)}
        </div>
        <div style={{ marginBottom: 18 }}>
          <label style={{ fontSize: "var(--text-sm)", fontWeight: 600, color: "var(--text-heading)", display: "block", marginBottom: 8 }}>Signature</label>
          <RSignaturePad onChange={setHasSig} />
        </div>
        <div style={{ marginBottom: 22 }}>
          <Checkbox checked={agreed} onChange={(e) => setAgreed(e.target.checked)}
            label="I have read this document and sign it freely."
            description={`Signing as ${residentName} · ${new Date().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}`} />
        </div>
        <Button variant="primary" size="lg" fullWidth disabled={!canSign} onClick={onSigned}
          leftIcon={<RIcon name="pen-line" size={18} />}>Sign & submit</Button>
      </Card>
    </div>
  );
}

window.WCPortal.ResidentPortal = ResidentPortal;
