// Woodbury Operator — Ticket Detail (progress tracker). Registers window.TicketDetailScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, CardHeader, Button, Badge, Avatar, IconTile, Eyebrow, Modal, Select, Textarea, Input } = NS;

  // Progress stages a ticket moves through.
  const STAGES = ["Reported", "Vendor Assigned", "Scheduled", "In Progress", "Resolved"];

  function TicketDetailScreen({ onBack }) {
    const seed = window.WB_ACTIVE_TICKET || {
      unit: "House 1 — AC Leak", asset: "Lashibi Townhouses", icon: "wind", badge: "Urgent", badgeTone: "danger",
      vendor: "AirCool HVAC Services", vendorTrade: "HVAC", vendorPhone: "+233 55 880 9910",
      tenant: "Kofi Mensah", tenantUnit: "House 1", reported: "18 Aug 2026 · 09:12",
      reportDate: "20 Aug 2026", priority: "Urgent", stageIndex: 1,
      description: "Unit making a loud grinding noise and not cooling. Started overnight.",
    };
    const [stage, setStage] = React.useState(seed.stageIndex || 1);
    const [log, setLog] = React.useState([
      { icon: "user-check", tone: "accent", title: "Vendor assigned", body: seed.vendor + " assigned to the ticket.", time: "18 Aug · 09:40" },
      { icon: "wrench", tone: "danger", title: "Ticket reported", body: seed.description, time: seed.reported },
    ]);
    const [update, setUpdate] = React.useState(false);
    const [uStage, setUStage] = React.useState(STAGES[Math.min(stage + 1, STAGES.length - 1)]);
    const [uNote, setUNote] = React.useState("");
    const [notifyTenant, setNotifyTenant] = React.useState(true);

    const applyUpdate = () => {
      const idx = STAGES.indexOf(uStage);
      setStage(idx);
      setLog((l) => [{ icon: "activity", tone: "brand", title: "Status → " + uStage, body: uNote || "Progress updated.", time: "Just now" }, ...l]);
      setUpdate(false); setUNote("");
      window.WBToast(notifyTenant ? "Progress updated · " + seed.tenant + " notified" : "Progress updated");
    };

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 24, padding: "36px 40px", maxWidth: 1200 }}>
        <window.WBPageHeader eyebrow="Maintenance Ticket" title={seed.unit}
          sub={seed.asset + " · reported " + seed.reported}
          actions={<React.Fragment>
            <Button variant="secondary" icon="arrow-left" onClick={onBack}>Back</Button>
            <Button variant="primary" icon="refresh-cw" onClick={() => { setUStage(STAGES[Math.min(stage + 1, STAGES.length - 1)]); setUpdate(true); }}>Update Progress</Button>
          </React.Fragment>} />

        {/* Progress tracker */}
        <Card style={{ padding: 28 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 22, flexWrap: "wrap", gap: 12 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <IconTile icon={seed.icon} tone={seed.badgeTone === "danger" ? "danger" : "accent"} size={44} />
              <div><div style={{ fontWeight: 700, fontSize: 16, color: "var(--text-heading)" }}>{seed.priority} priority</div><div style={{ fontSize: 13, color: "var(--text-muted)" }}>Target report-back: {seed.reportDate}</div></div>
            </div>
            <Badge tone={stage >= 4 ? "success" : seed.badgeTone} dot={stage >= 4}>{STAGES[stage]}</Badge>
          </div>
          <div style={{ display: "flex", alignItems: "flex-start" }}>
            {STAGES.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: 96 }}>
                    <div style={{ width: 34, height: 34, 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: 16, height: 16 }}><i data-lucide={done ? "check" : active ? "loader" : "circle"}></i></span>
                    </div>
                    <span style={{ fontSize: 11, fontWeight: 600, textAlign: "center", color: done || active ? "var(--text-heading)" : "var(--text-muted)" }}>{s}</span>
                  </div>
                  {i < STAGES.length - 1 && <div style={{ flex: 1, height: 3, borderRadius: 9999, background: i < stage ? "var(--success)" : "var(--border)", marginTop: 15 }} />}
                </React.Fragment>
              );
            })}
          </div>
        </Card>

        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 24, alignItems: "start" }}>
          {/* Activity log */}
          <Card>
            <CardHeader title="Progress Log" action={<Button variant="secondary" size="sm" icon="plus" onClick={() => { setUStage(STAGES[stage]); setUpdate(true); }}>Add Update</Button>} />
            <div style={{ padding: "24px 28px" }}>
              {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 < log.length - 1 && <div style={{ flex: 1, width: 2, background: "var(--border)", margin: "4px 0" }} />}
                    </div>
                    <div style={{ flex: 1, paddingBottom: i < 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>

          {/* Vendor + tenant + resolve */}
          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            <Card style={{ padding: 24 }}>
              <Eyebrow>Assigned Vendor</Eyebrow>
              <div style={{ display: "flex", alignItems: "center", gap: 14, margin: "14px 0 16px" }}>
                <IconTile icon="hard-hat" tone="brand" size={44} />
                <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{seed.vendor}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{seed.vendorTrade} · {seed.vendorPhone}</div></div>
              </div>
              <Button variant="secondary" size="sm" full icon="refresh-cw" onClick={() => window.WBToast("Reassign from the Maintenance queue")}>Reassign Vendor</Button>
            </Card>
            <Card style={{ padding: 24 }}>
              <Eyebrow>Reported By</Eyebrow>
              <div style={{ display: "flex", alignItems: "center", gap: 14, margin: "14px 0 16px" }}>
                <Avatar name={seed.tenant} src="../../assets/images/av-kofi.jpg" size={44} />
                <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{seed.tenant}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{seed.tenantUnit}</div></div>
              </div>
              <Button variant="secondary" size="sm" full icon="message-square" onClick={() => window.WBToast("Messaging " + seed.tenant)}>Message Tenant</Button>
            </Card>
            {stage < 4 && <Button variant="primary" full icon="check-check" onClick={() => { setStage(4); setLog((l) => [{ icon: "check-check", tone: "success", title: "Status → Resolved", body: "Ticket closed and signed off.", time: "Just now" }, ...l]); window.WBToast("Ticket resolved · " + seed.tenant + " notified"); }}>Mark Resolved</Button>}
          </div>
        </div>

        {/* Update progress modal */}
        <Modal open={update} onClose={() => setUpdate(false)} icon="refresh-cw" title="Update Progress" subtitle={seed.unit}
          footer={<React.Fragment><Button variant="secondary" onClick={() => setUpdate(false)}>Cancel</Button><Button variant="primary" icon="check" onClick={applyUpdate}>Post Update</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Select label="New status" value={uStage} onChange={(e) => setUStage(e.target.value)} options={STAGES} />
            <Input label="Report-back date" type="date" />
            <Textarea label="Update note" placeholder="e.g. Vendor inspected; compressor part ordered, ETA 2 days." value={uNote} onChange={(e) => setUNote(e.target.value)} />
            <label style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer" }}>
              <input type="checkbox" checked={notifyTenant} onChange={(e) => setNotifyTenant(e.target.checked)} style={{ accentColor: "var(--brand)", width: 16, height: 16 }} />
              <span style={{ fontSize: 14, color: "var(--text-heading)" }}>Notify {seed.tenant} of this update (SMS + portal)</span>
            </label>
          </div>
        </Modal>
      </div>
    );
  }
  window.TicketDetailScreen = TicketDetailScreen;
})();
