// Woodbury Resident — Requests (list + detail + new). Registers window.RRequests.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, CardHeader, Button, Badge, IconTile, Eyebrow, Modal, Select, Textarea, Input } = NS;

  function Tracker({ stage }) {
    const S = window.WBR.stages;
    return (
      <div style={{ display: "flex", alignItems: "flex-start" }}>
        {S.map((s, i) => {
          const done = i < stage, active = i === stage;
          return (
            <React.Fragment key={s}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8, flexShrink: 0, width: 84 }}>
                <div style={{ width: 32, height: 32, borderRadius: 9999, display: "flex", alignItems: "center", justifyContent: "center", background: done ? "var(--success)" : active ? "var(--brand)" : "var(--cream-100)", color: done || active ? "var(--cream-50)" : "var(--text-muted)", boxShadow: active ? "0 0 0 4px var(--brand-tint)" : "none" }}>
                  <span className="wb-ico" style={{ width: 15, height: 15 }}><i data-lucide={done ? "check" : active ? "loader" : "circle"}></i></span>
                </div>
                <span style={{ fontSize: 10.5, fontWeight: 600, textAlign: "center", color: done || active ? "var(--text-heading)" : "var(--text-muted)" }}>{s}</span>
              </div>
              {i < S.length - 1 && <div style={{ flex: 1, height: 3, borderRadius: 9999, background: i < stage ? "var(--success)" : "var(--border)", marginTop: 14 }} />}
            </React.Fragment>
          );
        })}
      </div>
    );
  }

  function RRequests({ focusId, onClear }) {
    const R = window.WBR;
    const loadingList = window.WBRuseLoad();
    const [extra, setExtra] = React.useState([]);
    const [form, setForm] = React.useState({ title: "", cat: "Plumbing", priority: "Medium", desc: "" });
    const myRequests = [...extra, ...R.requests];
    const submitRequest = () => {
      const id = "MR-" + Math.floor(2100 + Math.random() * 800);
      const iconMap = { "Plumbing": "droplet", "HVAC / Cooling": "wind", "Electrical": "zap", "Appliances": "wifi", "Structural": "home", "General": "wrench" };
      const rec = { id, title: form.title || "New request", cat: form.cat, icon: iconMap[form.cat] || "wrench", stage: 0, priority: form.priority, tone: form.priority === "Urgent" ? "danger" : form.priority === "Medium" ? "accent" : "success", desc: form.desc || "", vendor: "Awaiting assignment", reported: "Just now", log: [{ icon: "wrench", tone: "brand", title: "Request submitted", body: "You reported this issue.", time: "Just now" }] };
      setExtra((l) => [rec, ...l]);
      // Bridge to the operator portal (same-origin localStorage channel).
      try {
        const key = "wb_portal_requests";
        const q = JSON.parse(localStorage.getItem(key) || "[]");
        q.unshift({ id, title: rec.title, cat: form.cat, priority: form.priority, unit: R.resident.unit, property: R.resident.property, resident: R.resident.name, reported: "Just now" });
        localStorage.setItem(key, JSON.stringify(q));
      } catch (e) {}
      // Write-through to the dev backend (resident -> operator bridge via dev.api).
      if (window.WBRsubmitRequest) window.WBRsubmitRequest({ title: rec.title, cat: form.cat, priority: form.priority, desc: form.desc, icon: rec.icon });
      setForm({ title: "", cat: "Plumbing", priority: "Medium", desc: "" });
      setNw(false); window.WBRToast("Request submitted — the office has been notified");
    };
    const [sel, setSel] = React.useState(focusId || null);
    const [nw, setNw] = React.useState(false);
    React.useEffect(() => { if (focusId) { setSel(focusId); onClear && onClear(); } }, [focusId]);
    const current = myRequests.find((r) => r.id === sel);

    if (current) {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 24, padding: "36px 40px", maxWidth: 1000 }}>
          <window.WBRHeader eyebrow={current.id} title={current.title} sub={current.cat + " · reported " + current.reported}
            actions={<Button variant="secondary" icon="arrow-left" onClick={() => setSel(null)}>Back</Button>} />
          <Card style={{ padding: 28 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 22, flexWrap: "wrap", gap: 12 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}><IconTile icon={current.icon} tone={current.tone} size={44} /><div><div style={{ fontWeight: 700, fontSize: 16, color: "var(--text-heading)" }}>{current.priority} priority</div><div style={{ fontSize: 13, color: "var(--text-muted)" }}>Assigned to {current.vendor}</div></div></div>
              <Badge tone={current.stage >= 4 ? "success" : current.tone === "danger" ? "danger" : "warning"} dot={current.stage >= 4}>{R.stages[current.stage]}</Badge>
            </div>
            <Tracker stage={current.stage} />
          </Card>
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 24, alignItems: "start" }}>
            <Card>
              <CardHeader title="Progress Updates" />
              <div style={{ padding: "24px 28px" }}>
                {current.log.map((e, i) => {
                  const tones = { danger: ["var(--danger-bg)", "var(--danger)"], brand: ["var(--walnut-100)", "var(--walnut-700)"], accent: ["rgba(194,125,72,0.14)", "var(--terracotta-600)"], success: ["var(--success-bg)", "var(--success)"] }[e.tone] || ["var(--cream-100)", "var(--gray-500)"];
                  return (
                    <div key={i} style={{ display: "flex", gap: 16 }}>
                      <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                        <div style={{ width: 36, height: 36, borderRadius: "var(--radius-md)", background: tones[0], display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><span className="wb-ico" style={{ width: 16, height: 16, color: tones[1] }}><i data-lucide={e.icon}></i></span></div>
                        {i < current.log.length - 1 && <div style={{ flex: 1, width: 2, background: "var(--border)", margin: "4px 0" }} />}
                      </div>
                      <div style={{ flex: 1, paddingBottom: i < current.log.length - 1 ? 20 : 0 }}><div style={{ display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}><span style={{ fontWeight: 700, fontSize: 14, color: "var(--text-heading)" }}>{e.title}</span><span style={{ fontSize: 12, color: "var(--text-muted)" }}>{e.time}</span></div><p style={{ margin: "3px 0 0", fontSize: 13, lineHeight: 1.5, color: "var(--text-body)" }}>{e.body}</p></div>
                    </div>
                  );
                })}
              </div>
            </Card>
            <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
              <Card style={{ padding: 24 }}><Eyebrow>Details</Eyebrow><p style={{ margin: "12px 0 0", fontSize: 14, lineHeight: 1.6, color: "var(--text-body)" }}>{current.desc}</p></Card>
              <Card style={{ padding: 24 }}>
                <Eyebrow>Need to add something?</Eyebrow>
                <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 10 }}>
                  <Button variant="secondary" size="sm" full icon="message-square" onClick={() => window.WBRToast("Message sent to the office")}>Message Office</Button>
                  {current.stage < 4 && <Button variant="ghost" size="sm" full icon="x" onClick={() => window.WBRToast("Cancellation requested", "danger")}>Cancel Request</Button>}
                </div>
              </Card>
            </div>
          </div>
        </div>
      );
    }

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 24, padding: "36px 40px", maxWidth: 1000 }}>
        <window.WBRHeader eyebrow="Maintenance" title="My Requests" sub="Track every repair request for your unit."
          actions={<Button variant="primary" icon="plus" onClick={() => setNw(true)}>New Request</Button>} />
        <Card>
          <CardHeader title="All Requests" action={<Badge tone="neutral">{myRequests.length}</Badge>} />
          {loadingList ? <window.WBRSkeleton rows={3} /> : myRequests.length === 0 ? (
            <window.WBREmpty icon="wrench" title="No requests yet" message="Log a maintenance issue and track it here step by step." action={<Button variant="primary" size="sm" icon="plus" onClick={() => setNw(true)}>New Request</Button>} />
          ) : myRequests.map((r, i) => (
            <div key={r.id} onClick={() => setSel(r.id)} style={{ display: "flex", gap: 14, alignItems: "center", padding: "18px 24px", borderTop: i ? "1px solid var(--border)" : "none", cursor: "pointer" }}>
              <IconTile icon={r.icon} tone={r.stage >= 4 ? "success" : r.tone} size={44} />
              <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{r.title}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{r.id} · {r.cat} · reported {r.reported}</div></div>
              <Badge tone={r.stage >= 4 ? "success" : r.tone === "danger" ? "danger" : "warning"} dot={r.stage >= 4}>{R.stages[r.stage]}</Badge>
              <span className="wb-ico" style={{ width: 18, height: 18, color: "var(--text-muted)" }}><i data-lucide="chevron-right"></i></span>
            </div>
          ))}
        </Card>

        <Modal open={nw} onClose={() => setNw(false)} icon="wrench" title="New Maintenance Request" subtitle="Tell us what needs fixing in your unit."
          footer={<React.Fragment><Button variant="secondary" onClick={() => setNw(false)}>Cancel</Button><Button variant="primary" icon="check" onClick={submitRequest}>Submit Request</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Input label="Issue title" placeholder="e.g. Kitchen tap leaking" value={form.title} onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))} />
            <div style={{ display: "flex", gap: 14 }}>
              <Select label="Category" value={form.cat} onChange={(e) => setForm((f) => ({ ...f, cat: e.target.value }))} options={["Plumbing", "HVAC / Cooling", "Electrical", "Appliances", "Structural", "General"]} containerStyle={{ flex: 1 }} />
              <Select label="Priority" value={form.priority} onChange={(e) => setForm((f) => ({ ...f, priority: e.target.value }))} options={["Low", "Medium", "Urgent"]} containerStyle={{ flex: 1 }} />
            </div>
            <Textarea label="Description" placeholder="Describe the issue and when it started…" value={form.desc} onChange={(e) => setForm((f) => ({ ...f, desc: e.target.value }))} />
            <window.WBImageUpload label="Add photos (optional)" />
          </div>
        </Modal>
      </div>
    );
  }
  window.RRequests = RRequests;
})();
