/* Willow Creek Portal — shared helpers: Icon, SignaturePad, demo store. */
const { useState, useEffect, useRef, useLayoutEffect } = React;

function PIcon({ name, size = 20, color = "currentColor", strokeWidth = 2, style }) {
  const ref = useRef(null);
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el || !window.lucide) return;
    el.innerHTML = "";
    const i = document.createElement("i");
    i.setAttribute("data-lucide", name);
    el.appendChild(i);
    window.lucide.createIcons({
      attrs: { width: size, height: size, stroke: color, "stroke-width": strokeWidth },
      nameAttr: "data-lucide",
    });
  }, [name, size, color, strokeWidth]);
  return <span ref={ref} aria-hidden="true" style={{ display: "inline-flex", width: size, height: size, flexShrink: 0, ...style }} />;
}

/* ---- Draw-to-sign pad ---- */
function SignaturePad({ onChange, height = 130 }) {
  const canvasRef = useRef(null);
  const [empty, setEmpty] = useState(true);
  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    const r = canvas.getBoundingClientRect();
    canvas.width = r.width * 2; canvas.height = r.height * 2;
    ctx.scale(2, 2);
    ctx.strokeStyle = "#0f120e"; ctx.lineWidth = 2.2; ctx.lineCap = "round"; ctx.lineJoin = "round";
    let drawing = false;
    const pos = (e) => {
      const rect = canvas.getBoundingClientRect();
      const p = e.touches ? e.touches[0] : e;
      return { x: p.clientX - rect.left, y: p.clientY - rect.top };
    };
    const down = (e) => { drawing = true; const p = pos(e); ctx.beginPath(); ctx.moveTo(p.x, p.y); e.preventDefault(); };
    const move = (e) => {
      if (!drawing) return;
      const p = pos(e); ctx.lineTo(p.x, p.y); ctx.stroke();
      setEmpty(false); onChange && onChange(true);
      e.preventDefault();
    };
    const up = () => { drawing = false; };
    canvas.addEventListener("pointerdown", down);
    canvas.addEventListener("pointermove", move);
    window.addEventListener("pointerup", up);
    return () => {
      canvas.removeEventListener("pointerdown", down);
      canvas.removeEventListener("pointermove", move);
      window.removeEventListener("pointerup", up);
    };
  }, []);
  const clear = () => {
    const canvas = canvasRef.current;
    canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
    setEmpty(true); onChange && onChange(false);
  };
  return (
    <div>
      <canvas ref={canvasRef} style={{
        width: "100%", height, borderRadius: "var(--radius-md)", touchAction: "none",
        background: "var(--surface-raised)", border: "1.5px dashed var(--border-strong)", cursor: "crosshair",
      }} />
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
        <span style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>
          {empty ? "Sign above with your mouse or finger" : "Signature captured"}
        </span>
        <button onClick={clear} style={{ background: "none", border: "none", cursor: "pointer",
          color: "var(--text-link)", fontSize: "var(--text-sm)", fontWeight: 600, fontFamily: "var(--font-sans)" }}>Clear</button>
      </div>
    </div>
  );
}

/* ---- Demo data store (in-memory + localStorage) ---- */
const PORTAL_KEY = "wc_portal_v3";
const defaultStore = {
  houses: [
    { id: "h1", name: "Creekside House", manager: "James Ortiz", address: "2013 Mark Twain Lane", beds: [
      { id: "b1", label: "Room 1 · Bed A", resident: "Marcus Reed" },
      { id: "b2", label: "Room 1 · Bed B", resident: "Devon King" },
      { id: "b3", label: "Room 2 · Bed A", resident: "Theo Lang" },
      { id: "b4", label: "Room 2 · Bed B", resident: null },
    ]},
    { id: "h2", name: "Willow House", manager: "Nadia Brooks", address: "1426 Creekside Drive", beds: [
      { id: "b5", label: "Room 1 · Bed A", resident: "Sam Whitfield" },
      { id: "b6", label: "Room 1 · Bed B", resident: null },
      { id: "b7", label: "Room 2 · Bed A", resident: null },
    ]},
  ],
  staff: ["James Ortiz", "Nadia Brooks", "Rebecca Hale", "Sam Whitfield"],
  residents: [
    { id: "r1", name: "Marcus Reed", phone: "(940) 555-0181", house: "Creekside House", phase: 2, status: "Active", balance: 0 },
    { id: "r2", name: "Devon King", phone: "(940) 555-0163", house: "Creekside House", phase: 1, status: "Active", balance: 175 },
    { id: "r3", name: "Theo Lang", phone: "(940) 555-0129", house: "Creekside House", phase: 3, status: "Active", balance: 0 },
    { id: "r4", name: "Sam Whitfield", phone: "(940) 555-0147", house: "Willow House", phase: 2, status: "Active", balance: 350 },
    { id: "r5", name: "Alex Monroe", phone: "(940) 555-0173", house: "Awaiting bed", phase: 1, status: "Onboarding", balance: 175 },
  ],
  applications: [
    { id: "a1", name: "Jordan Rivera", submitted: "Jul 1", situation: "Leaving residential treatment", status: "pending" },
    { id: "a2", name: "Chris Delgado", submitted: "Jun 30", situation: "Just completed detox", status: "pending" },
    { id: "a3", name: "Alex Monroe", submitted: "Jun 28", situation: "Sober but need structure", status: "approved" },
  ],
  forms: [
    { id: "f1", title: "Resident Agreement & House Rules Waiver", kind: "waiver", required: true, status: "published",
      body: "I understand and agree to the house rules of Willow Creek Sober Living, including complete abstinence from alcohol and non-prescribed drugs, participation in house meetings and chores, curfew by phase, and respect for housemates and staff. I understand that violation of these agreements may result in discharge from the residence.",
      fields: [{ label: "Full legal name", type: "text" }, { label: "Date of birth", type: "date" }] },
    { id: "f2", title: "Liability & Activities Waiver", kind: "waiver", required: true, status: "published",
      body: "I release Willow Creek Sober Living, its staff and volunteers from liability for personal injury or loss of property arising from ordinary house activities, transportation to meetings, and recreational outings, except in cases of gross negligence.",
      fields: [{ label: "Full legal name", type: "text" }, { label: "Emergency contact & phone", type: "text" }] },
    { id: "f3", title: "Declaration of Sobriety Commitment", kind: "declaration", required: true, status: "published",
      body: "I declare my commitment to my recovery: to remain abstinent, to be honest with my house community, to attend agreed meetings, and to ask for help when I am struggling. I make this declaration freely, for myself.",
      fields: [{ label: "Full legal name", type: "text" }, { label: "Sobriety date", type: "date" }] },
    { id: "f4", title: "Medical Information & Consent", kind: "form", required: false, status: "published",
      body: "Please share current medications, allergies, and conditions our house team should know about. This information is kept confidential and used only to keep you safe.",
      fields: [{ label: "Current medications", type: "textarea" }, { label: "Allergies", type: "text" }, { label: "Primary physician", type: "text" }] },
    { id: "f5", title: "Photo & Media Release", kind: "form", required: false, status: "draft",
      body: "I grant / do not grant permission for Willow Creek to use photographs that include me in community materials. Consent may be withdrawn at any time in writing.",
      fields: [{ label: "Full legal name", type: "text" }] },
  ],
  signedForms: { "Marcus Reed": ["f1", "f2", "f3", "f4"], "Devon King": ["f1"], "Sam Whitfield": ["f1", "f2"], "Alex Monroe": ["f1", "f2", "f3", "f4"] },
  payments: [
    { id: "p1", resident: "Marcus Reed", date: "Jun 23, 2026", amount: 175, method: "Visa ··4242", status: "Paid", receiptNo: "WC-2026-1074" },
    { id: "p2", resident: "Marcus Reed", date: "Jun 16, 2026", amount: 175, method: "Visa ··4242", status: "Paid", receiptNo: "WC-2026-0961" },
    { id: "p3", resident: "Devon King", date: "Jun 16, 2026", amount: 175, method: "Cash", status: "Paid", receiptNo: "WC-2026-0958" },
  ],
  cms: {
    heroHeadline: "A calmer place to begin again.",
    heroSub: "Structured, supportive recovery housing where accountability meets belonging — so early sobriety has room to take root.",
    weeklyRate: 175, depositFee: 150, lateFee: 25, bedsOpenNote: "3 beds open this week", phone: "(940) 555-0142",
  },
};

function loadStore() {
  try {
    const raw = localStorage.getItem(PORTAL_KEY);
    if (raw) return JSON.parse(raw);
  } catch (e) {}
  return JSON.parse(JSON.stringify(defaultStore));
}
function saveStore(s) { try { localStorage.setItem(PORTAL_KEY, JSON.stringify(s)); } catch (e) {} }

/* ---- Receipts ---- */
function makeReceiptNo() {
  return "WC-" + new Date().getFullYear() + "-" + String(Math.floor(1000 + Math.random() * 9000));
}

function ReceiptModal({ payment, cms, onClose, onRegenerate }) {
  const { Button, Badge } = window.WillowCreekDesignSystem_90378c;
  const printReceipt = () => {
    const w = window.open("", "_blank", "width=420,height=640");
    if (!w) return;
    w.document.write(`<!DOCTYPE html><html><head><title>Receipt ${payment.receiptNo}</title>
<style>body{font-family:-apple-system,'Hanken Grotesk',sans-serif;color:#1f261e;padding:34px;max-width:400px;margin:0 auto}
h1{font-size:19px;margin:16px 0 2px}.m{color:#737c6c;font-size:12.5px}
.row{display:flex;justify-content:space-between;padding:9px 0;border-bottom:1px solid #ece4d5;font-size:13.5px}
.amt{font-size:30px;font-weight:800;margin:14px 0 2px}.paid{display:inline-block;background:#e4ebd6;color:#3a6244;font-weight:700;font-size:11px;padding:3px 10px;border-radius:99px;letter-spacing:.05em}
.ft{margin-top:22px;font-size:11px;color:#97a08c;line-height:1.5}</style></head><body>
<div style="font-weight:800;font-size:15px;color:#2d5138">❦ Willow Creek Sober Living</div>
<div class="m">2013 Mark Twain Lane · Denton, TX 76210 · ${cms.phone}</div>
<h1>Payment receipt</h1><div class="m">Receipt ${payment.receiptNo}</div>
<div class="amt">$${payment.amount}.00</div><span class="paid">PAID</span>
<div style="margin-top:18px">
<div class="row"><span>Resident</span><strong>${payment.resident}</strong></div>
<div class="row"><span>Description</span><strong>Weekly program fee</strong></div>
<div class="row"><span>Date</span><strong>${payment.date}</strong></div>
<div class="row"><span>Method</span><strong>${payment.method}</strong></div>
<div class="row"><span>Processed by</span><strong>Stripe</strong></div>
</div>
<p class="ft">Thank you. This receipt was generated by the Willow Creek resident portal and can be regenerated at any time by the resident or an administrator. Demo document — no real charge was made.</p>
<script>window.onload=function(){window.print()}<\/script></body></html>`);
    w.document.close();
  };
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 300, background: "rgba(31,38,30,.5)",
      backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: 420, background: "var(--surface-raised)",
        borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-float)", padding: "30px 30px 24px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <img src="../assets/logo-wordmark.svg" alt="Willow Creek" style={{ height: 34 }} />
          <button onClick={onClose} aria-label="Close" style={{ background: "none", border: "none", cursor: "pointer", color: "var(--text-muted)", fontSize: 20, lineHeight: 1 }}>×</button>
        </div>
        <h3 style={{ margin: "18px 0 2px", fontSize: "var(--text-xl)" }}>Payment receipt</h3>
        <div style={{ fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>Receipt {payment.receiptNo}</div>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 38, color: "var(--brand-primary)", margin: "14px 0 4px" }}>${payment.amount}.00</div>
        <Badge variant="success" dot>Paid</Badge>
        <div style={{ margin: "18px 0 20px" }}>
          {[["Resident", payment.resident], ["Description", "Weekly program fee"], ["Date", payment.date], ["Method", payment.method], ["Processed by", "Stripe"]].map(([k, v]) => (
            <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "9px 0", borderBottom: "1px solid var(--border-subtle)", fontSize: "var(--text-sm)" }}>
              <span style={{ color: "var(--text-muted)" }}>{k}</span>
              <strong style={{ color: "var(--text-heading)" }}>{v}</strong>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          {onRegenerate && (
            <Button variant="secondary" style={{ flex: 1 }} onClick={onRegenerate}
              leftIcon={<PIcon name="refresh-cw" size={15} />}>Regenerate</Button>
          )}
          <Button variant="primary" style={{ flex: 1 }} onClick={printReceipt}
            leftIcon={<PIcon name="printer" size={15} />}>Print / save PDF</Button>
        </div>
        <p style={{ fontSize: 11, color: "var(--text-subtle)", textAlign: "center", margin: "14px 0 0", lineHeight: 1.5 }}>
          Receipts can be regenerated any time — by you or by the house team. Demo document.
        </p>
      </div>
    </div>
  );
}

/* Small UI atoms shared by both portals */
function PSection({ title, action, children, style }) {
  return (
    <section style={{ marginBottom: 28, ...style }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
        <h3 style={{ margin: 0, fontSize: "var(--text-lg)", letterSpacing: "0.02em" }}>{title}</h3>
        {action}
      </div>
      {children}
    </section>
  );
}

function KindBadge({ kind }) {
  const { Badge } = window.WillowCreekDesignSystem_90378c;
  const map = { waiver: ["clay", "Waiver"], declaration: ["water", "Declaration"], form: ["forest", "Form"] };
  const [variant, label] = map[kind] || map.form;
  return <Badge variant={variant} size="sm">{label}</Badge>;
}

window.WCPortal = { PIcon, SignaturePad, loadStore, saveStore, PSection, KindBadge, PORTAL_KEY, makeReceiptNo, ReceiptModal };
