/* ============================================================
   FacilityOS — Work Order detail screen
   ============================================================ */
window.Screens = window.Screens || {};

function MetaRow({ icon, label, children }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 0", borderBottom: "1px solid var(--border)" }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 9, fontSize: 13, color: "var(--text-faint)", fontWeight: 500, width: 118, flex: "0 0 auto" }}>
        <Icon name={icon} size={15} />{label}
      </span>
      <div style={{ flex: 1, textAlign: "right", fontSize: 13.5, fontWeight: 600 }}>{children}</div>
    </div>
  );
}

Screens.WODetail = function WODetail({ go, params }) {
  const DB = window.DB;
  const { Card, Button, StatusBadge, PriorityPill, Avatar, SectionHead } = UI;
  const wo = DB.woDetail(params.id || "WO-2148");
  const f = DB.facById(wo.facility);
  const tech = DB.techById(wo.assignee);
  const [checks, setChecks] = useState(wo.checklist.map((c) => c.done));
  const [status, setStatus] = useState(wo.status);
  const [note, setNote] = useState("");

  const doneCount = checks.filter(Boolean).length;
  const pct = Math.round((doneCount / checks.length) * 100);

  return (
    <div className="page fade-up">
      {/* breadcrumb + header */}
      <button onClick={() => go("work-orders")} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "transparent", border: "none", cursor: "pointer", color: "var(--text-muted)", fontSize: 13, fontWeight: 600, marginBottom: 14, padding: 0 }}>
        <Icon name="chevLeft" size={16} /> Work Orders
      </button>

      <div style={{ display: "flex", alignItems: "flex-start", gap: 16, flexWrap: "wrap", marginBottom: 20 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8, flexWrap: "wrap" }}>
            <span className="mono" style={{ fontSize: 13, fontWeight: 600, color: "var(--text-faint)" }}>{wo.id}</span>
            <PriorityPill priority={wo.priority} />
            <StatusBadge status={status} />
          </div>
          <h1 style={{ margin: 0, fontSize: "clamp(20px, 3vw, 26px)", fontWeight: 700, letterSpacing: "-.025em", lineHeight: 1.2 }}>{wo.title}</h1>
          <div style={{ marginTop: 8, display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--text-muted)", flexWrap: "wrap" }}>
            <Icon name="pin" size={15} /> {f.name} <span style={{ color: "var(--border-strong)" }}>·</span> {wo.asset}
          </div>
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <Button variant="default" icon="edit">Edit</Button>
          <Button variant="primary" icon="check">Update Status</Button>
        </div>
      </div>

      <div className="detail-grid" style={{ display: "grid", gridTemplateColumns: "minmax(0,1.6fr) minmax(0,1fr)", gap: 18, alignItems: "start" }}>
        {/* LEFT */}
        <div style={{ display: "flex", flexDirection: "column", gap: 18, minWidth: 0 }}>
          {/* status stepper */}
          <Card>
            <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
              {["open", "in_progress", "on_hold", "completed"].map((s, i) => {
                const order = { open: 0, in_progress: 1, on_hold: 1, completed: 3 };
                const cur = order[status];
                const active = order[s] <= cur && !(s === "on_hold" && status !== "on_hold");
                const isCur = s === status;
                return (
                  <React.Fragment key={s}>
                    <button onClick={() => setStatus(s)} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 7, background: "transparent", border: "none", cursor: "pointer", padding: "2px 0" }}>
                      <span style={{ width: 30, height: 30, borderRadius: 99, display: "flex", alignItems: "center", justifyContent: "center",
                        background: isCur ? "var(--accent)" : active ? UI.tint("--accent", 22) : "var(--surface-3)",
                        color: isCur ? "var(--accent-fg)" : active ? "var(--accent-strong)" : "var(--text-faint)",
                        border: isCur ? "none" : "1px solid var(--border)", fontWeight: 700, fontSize: 13 }}>
                        {active && !isCur ? <Icon name="check" size={15} stroke={3} /> : i + 1}
                      </span>
                      <span style={{ fontSize: 11.5, fontWeight: isCur ? 700 : 500, color: isCur ? "var(--text)" : "var(--text-faint)" }}>{DB.STATUS[s].label}</span>
                    </button>
                    {i < 3 && <span style={{ flex: "0 0 auto", height: 2, width: "100%", maxWidth: 60, background: order[s] < cur ? "var(--accent)" : "var(--border)", marginBottom: 22, borderRadius: 99 }} />}
                  </React.Fragment>
                );
              })}
            </div>
          </Card>

          <Card>
            <SectionHead title="Description" />
            <p style={{ margin: 0, fontSize: 14, lineHeight: 1.65, color: "var(--text-muted)", textWrap: "pretty" }}>{wo.description}</p>
          </Card>

          {/* checklist */}
          <Card>
            <SectionHead title="Checklist" sub={`${doneCount} of ${checks.length} complete`}
              action={<span className="tnum" style={{ fontSize: 18, fontWeight: 700, color: "var(--accent-strong)" }}>{pct}%</span>} />
            <div style={{ height: 7, borderRadius: 99, background: "var(--surface-3)", overflow: "hidden", marginBottom: 16 }}>
              <div style={{ height: "100%", width: `${pct}%`, background: "var(--accent)", borderRadius: 99, transition: "width .3s ease" }} />
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              {wo.checklist.map((c, i) => (
                <label key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "9px 8px", borderRadius: "var(--radius-sm)", cursor: "pointer" }}
                  onMouseEnter={(e)=>e.currentTarget.style.background="var(--surface-2)"} onMouseLeave={(e)=>e.currentTarget.style.background="transparent"}>
                  <span onClick={() => { const n = [...checks]; n[i] = !n[i]; setChecks(n); }} style={{
                    width: 20, height: 20, borderRadius: 6, flex: "0 0 auto", display: "inline-flex", alignItems: "center", justifyContent: "center",
                    border: `1.5px solid ${checks[i] ? "var(--c-done)" : "var(--border-strong)"}`, background: checks[i] ? "var(--c-done)" : "transparent", color: "#fff", transition: "all .15s" }}>
                    {checks[i] && <Icon name="check" size={14} stroke={3} />}
                  </span>
                  <span style={{ fontSize: 13.5, fontWeight: 500, color: checks[i] ? "var(--text-faint)" : "var(--text)", textDecoration: checks[i] ? "line-through" : "none" }}>{c.text}</span>
                </label>
              ))}
            </div>
          </Card>

          {/* attachments */}
          <Card>
            <SectionHead title="Photos & attachments" action={<Button size="sm" variant="soft" icon="paperclip">Upload</Button>} />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(130px, 1fr))", gap: 12 }}>
              {wo.attachments.map((a, i) => (
                <div key={i} style={{ borderRadius: "var(--radius-sm)", border: "1px solid var(--border)", overflow: "hidden", background: "var(--surface-2)" }}>
                  <div style={{ aspectRatio: "4/3", background: a.kind === "pdf" ? "var(--surface-3)" : `repeating-linear-gradient(135deg, var(--surface-3), var(--surface-3) 9px, color-mix(in oklch, var(--accent) 8%, var(--surface-3)) 9px, color-mix(in oklch, var(--accent) 8%, var(--surface-3)) 18px)`, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-faint)" }}>
                    <Icon name={a.kind === "pdf" ? "file" : "photo"} size={26} />
                  </div>
                  <div style={{ padding: "8px 10px", fontSize: 12, fontWeight: 500, color: "var(--text-muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }} className="mono">{a.name}</div>
                </div>
              ))}
              <button style={{ aspectRatio: "4/3", borderRadius: "var(--radius-sm)", border: "1.5px dashed var(--border-strong)", background: "transparent", cursor: "pointer", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 6, color: "var(--text-faint)", fontSize: 12, fontWeight: 600 }}>
                <Icon name="plus" size={20} /> Add
              </button>
            </div>
          </Card>

          {/* timeline */}
          <Card>
            <SectionHead title="Activity timeline" />
            <div style={{ display: "flex", flexDirection: "column" }}>
              {wo.timeline.map((e, i) => {
                const who = DB.techById(e.who);
                return (
                  <div key={i} style={{ display: "flex", gap: 13, paddingBottom: i === wo.timeline.length-1 ? 0 : 18 }}>
                    <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                      <Avatar id={e.who} size={30} />
                      {i !== wo.timeline.length-1 && <span style={{ flex: 1, width: 2, background: "var(--border)", marginTop: 4, borderRadius: 99 }} />}
                    </div>
                    <div style={{ paddingTop: 3, minWidth: 0 }}>
                      <div style={{ fontSize: 13.5, lineHeight: 1.45 }}><span style={{ fontWeight: 650 }}>{who ? who.name : "System"}</span> <span style={{ color: "var(--text-muted)" }}>{e.text}</span></div>
                      <div className="mono" style={{ fontSize: 11.5, color: "var(--text-faint)", marginTop: 2 }}>{e.time}</div>
                    </div>
                  </div>
                );
              })}
            </div>
            {/* add note */}
            <div style={{ marginTop: 16, display: "flex", gap: 10, alignItems: "flex-start" }}>
              <Avatar id="u0" size={30} />
              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 8 }}>
                <textarea value={note} onChange={(e) => setNote(e.target.value)} placeholder="Add a note or update…" rows={2} style={{ width: "100%", resize: "vertical", padding: "10px 12px", borderRadius: "var(--radius-sm)", border: "1px solid var(--border-strong)", background: "var(--surface-2)", color: "var(--text)", fontSize: 13.5, fontFamily: "var(--font-sans)", outline: "none" }} />
                <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                  <Button size="sm" variant="soft" icon="photo">Photo</Button>
                  <Button size="sm" variant="primary" icon="note" style={{ marginLeft: "auto", opacity: note ? 1 : 0.55 }}>Post note</Button>
                </div>
              </div>
            </div>
          </Card>
        </div>

        {/* RIGHT sidebar */}
        <div style={{ display: "flex", flexDirection: "column", gap: 18, minWidth: 0 }}>
          <Card>
            <SectionHead title="Details" />
            <MetaRow icon="user" label="Assignee">
              <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><Avatar id={wo.assignee} size={24} />{tech.name}</span>
            </MetaRow>
            <MetaRow icon="building" label="Facility">{f.name}</MetaRow>
            <MetaRow icon="box" label="Asset">{wo.asset}</MetaRow>
            <MetaRow icon="zap" label="Priority"><PriorityPill priority={wo.priority} /></MetaRow>
            <MetaRow icon="calendar" label="Created"><span className="mono">{wo.created}</span></MetaRow>
            <MetaRow icon="clock" label="Due"><span className="mono">{wo.due}</span></MetaRow>
            <MetaRow icon="clock" label="Est. hours"><span className="tnum">{wo.est} h</span></MetaRow>
            <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 0 2px" }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 9, fontSize: 13, color: "var(--text-faint)", fontWeight: 500, width: 118 }}><Icon name="dollar" size={15} />Est. cost</span>
              <div style={{ flex: 1, textAlign: "right" }}><span className="tnum" style={{ fontSize: 18, fontWeight: 700 }}>${wo.cost.toLocaleString()}</span></div>
            </div>
          </Card>

          <Card>
            <SectionHead title="Quick actions" />
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <Button variant="soft" icon="user" style={{ justifyContent: "flex-start" }}>Reassign technician</Button>
              <Button variant="soft" icon="calendarClock" style={{ justifyContent: "flex-start" }}>Reschedule</Button>
              <Button variant="soft" icon="clipboard" style={{ justifyContent: "flex-start" }}>Link checklist</Button>
              <Button variant="danger" icon="x" style={{ justifyContent: "flex-start" }}>Cancel work order</Button>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
};
