/* ============================================================
   FacilityOS — PM Schedules (calendar strip + templates + modal)
   ============================================================ */
window.Screens = window.Screens || {};

function FreqPill({ freq }) {
  const tok = window.DB.FREQ_TOKEN[freq] || "--c-low";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "2px 9px", borderRadius: 7, fontSize: 12, fontWeight: 600, color: `var(${tok})`, background: UI.tint(tok, 13), border: `1px solid ${UI.tint(tok, 26)}` }}>
      <Icon name="repeat" size={12} />{freq}
    </span>
  );
}

function CreatePMModal({ onClose }) {
  const DB = window.DB;
  const [freq, setFreq] = useState("Monthly");
  return (
    <React.Fragment>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "oklch(0 0 0 / 0.45)", backdropFilter: "blur(3px)", zIndex: 60, animation: "fadeIn .2s ease" }} />
      <div style={{ position: "fixed", inset: 0, zIndex: 61, display: "flex", alignItems: "center", justifyContent: "center", padding: 20, pointerEvents: "none" }}>
        <div style={{ width: "min(560px, 100%)", maxHeight: "90vh", overflowY: "auto", background: "var(--surface)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-lg)", border: "1px solid var(--border)", pointerEvents: "auto", animation: "scaleIn .22s cubic-bezier(.22,.61,.36,1)" }}>
          <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ width: 38, height: 38, borderRadius: "var(--radius-sm)", display: "flex", alignItems: "center", justifyContent: "center", background: UI.tint("--accent", 14), color: "var(--accent-strong)" }}><Icon name="calendarClock" size={20} /></span>
            <div style={{ flex: 1 }}><h2 style={{ margin: 0, fontSize: 17, fontWeight: 700, letterSpacing: "-.01em" }}>New PM Schedule</h2><p style={{ margin: "2px 0 0", fontSize: 12.5, color: "var(--text-faint)" }}>Set up a recurring preventive task</p></div>
            <UI.IconButton icon="x" onClick={onClose} />
          </div>
          <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
            <Field label="Schedule name"><input placeholder="e.g. Monthly HVAC filter replacement" style={inputStyle} /></Field>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <Field label="Facility"><select style={inputStyle} defaultValue="f3">{DB.facilities.map(f=><option key={f.id} value={f.id}>{f.name}</option>)}</select></Field>
              <Field label="Asset"><select style={inputStyle}>{DB.assets.slice(0,8).map(a=><option key={a.id}>{a.name}</option>)}</select></Field>
            </div>
            <Field label="Frequency">
              <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>
                {["Daily", "Weekly", "Monthly", "Quarterly", "Annual"].map((fr) => {
                  const on = freq === fr, tok = DB.FREQ_TOKEN[fr];
                  return <button key={fr} onClick={() => setFreq(fr)} style={{ padding: "8px 14px", borderRadius: "var(--radius-sm)", fontSize: 13, fontWeight: 600, cursor: "pointer", color: on ? `var(${tok})` : "var(--text-muted)", background: on ? UI.tint(tok, 13) : "var(--surface-2)", border: `1px solid ${on ? UI.tint(tok, 30) : "var(--border)"}` }}>{fr}</button>;
                })}
              </div>
            </Field>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <Field label="Start date"><input type="date" defaultValue="2026-06-01" style={inputStyle} /></Field>
              <Field label="Assign to"><select style={inputStyle}>{DB.techs.filter(t=>t.id!=="u0").map(t=><option key={t.id}>{t.name}</option>)}</select></Field>
            </div>
            <Field label="Linked checklist"><select style={inputStyle}>{DB.checklists.map(c=><option key={c.id}>{c.name}</option>)}</select></Field>
          </div>
          <div style={{ padding: "16px 24px", borderTop: "1px solid var(--border)", display: "flex", gap: 10, justifyContent: "flex-end" }}>
            <UI.Button variant="default" onClick={onClose}>Cancel</UI.Button>
            <UI.Button variant="primary" icon="check" onClick={onClose}>Create schedule</UI.Button>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}
const inputStyle = { width: "100%", height: 40, padding: "0 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" };
function Field({ label, children }) {
  return <label style={{ display: "block" }}><span style={{ display: "block", fontSize: 12.5, fontWeight: 600, color: "var(--text-muted)", marginBottom: 6 }}>{label}</span>{children}</label>;
}

Screens.PM = function PM({ go }) {
  const DB = window.DB;
  const { Card, Button, SectionHead, Avatar } = UI;
  const [modal, setModal] = useState(false);
  const [freqFilter, setFreqFilter] = useState("all");

  const list = DB.pmTemplates.filter((p) => freqFilter === "all" || p.freq === freqFilter);
  const avgComp = Math.round(DB.pmTemplates.reduce((s, p) => s + p.compliance, 0) / DB.pmTemplates.length);
  const dueThisWeek = DB.pmCalendar.reduce((s, d) => s + d.items.length, 0);

  return (
    <div className="page fade-up">
      {/* KPI strip */}
      <div className="kpi-grid" style={{ display: "grid", gridTemplateColumns: "repeat(4, minmax(0,1fr))", gap: 16, marginBottom: 18 }}>
        <UI.KpiCard icon="calendarClock" token="--accent" label="Active schedules" value={DB.pmTemplates.length} />
        <UI.KpiCard icon="clock" token="--c-high" label="Due this week" value={dueThisWeek} sub="next 7 days" />
        <UI.KpiCard icon="gauge" token="--c-done" label="Avg compliance" value={avgComp} suffix="%" delta={3} deltaGood />
        <UI.KpiCard icon="alert" token="--c-critical" label="Overdue" value="2" sub="needs rescheduling" />
      </div>

      {/* calendar strip */}
      <Card style={{ marginBottom: 18 }}>
        <SectionHead title="Next 7 days" sub="Upcoming preventive maintenance"
          action={<Button size="sm" variant="ghost" iconRight="calendar">Month view</Button>} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 10 }}>
          {DB.pmCalendar.map((d, i) => {
            const today = d.label === "Today";
            return (
              <div key={i} style={{ borderRadius: "var(--radius-sm)", border: `1px solid ${today ? UI.tint("--accent", 35) : "var(--border)"}`, background: today ? UI.tint("--accent", 7) : "var(--surface-2)", padding: 12, minHeight: 130, display: "flex", flexDirection: "column", gap: 8 }}>
                <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
                  <span style={{ fontSize: 11, fontWeight: 600, color: today ? "var(--accent-strong)" : "var(--text-faint)", textTransform: "uppercase", letterSpacing: ".04em" }}>{d.day}</span>
                  <span className="tnum" style={{ fontSize: 17, fontWeight: 700, color: today ? "var(--accent-strong)" : "var(--text)" }}>{d.date}</span>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  {d.items.map((id) => {
                    const pm = DB.pmTemplates.find((p) => p.id === id);
                    const tok = DB.FREQ_TOKEN[pm.freq];
                    return (
                      <button key={id} onClick={() => setModal(false)} style={{ textAlign: "left", padding: "6px 8px", borderRadius: 7, background: UI.tint(tok, 14), border: `1px solid ${UI.tint(tok, 26)}`, cursor: "pointer", borderLeft: `3px solid var(${tok})` }}>
                        <div style={{ fontSize: 11.5, fontWeight: 650, color: "var(--text)", lineHeight: 1.3, overflow: "hidden", textOverflow: "ellipsis", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>{pm.title}</div>
                      </button>
                    );
                  })}
                  {d.items.length === 0 && <span style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 4 }}>—</span>}
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      {/* templates list */}
      <Card pad={false} style={{ overflow: "hidden" }}>
        <div style={{ padding: "16px 18px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
          <h3 style={{ margin: 0, fontSize: 15.5, fontWeight: 650 }}>PM Templates</h3>
          <div style={{ display: "flex", gap: 6, marginLeft: 6 }}>
            {["all", "Weekly", "Monthly", "Quarterly", "Annual"].map((fr) => {
              const on = freqFilter === fr;
              return <button key={fr} onClick={() => setFreqFilter(fr)} style={{ padding: "5px 11px", borderRadius: 999, fontSize: 12, fontWeight: 600, cursor: "pointer", color: on ? "var(--accent-strong)" : "var(--text-muted)", background: on ? UI.tint("--accent", 12) : "transparent", border: `1px solid ${on ? UI.tint("--accent", 28) : "var(--border)"}` }}>{fr === "all" ? "All" : fr}</button>;
            })}
          </div>
          <Button variant="primary" icon="plus" size="sm" style={{ marginLeft: "auto" }} onClick={() => setModal(true)}>New Schedule</Button>
        </div>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 860 }}>
            <thead>
              <tr>
                {["Schedule", "Frequency", "Asset / Facility", "Owner", "Next due", "Compliance"].map((h, i) => (
                  <th key={h} className={i===2?"hide-md":""} style={{ textAlign: i===5?"right":"left", padding: "11px 16px", fontSize: 11.5, fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--text-faint)", borderBottom: "1px solid var(--border)", background: "var(--surface-2)", whiteSpace: "nowrap" }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {list.map((p, i) => {
                const f = DB.facById(p.facility), a = DB.assetById(p.asset);
                const compTok = p.compliance >= 90 ? "--c-done" : p.compliance >= 80 ? "--c-medium" : "--c-high";
                const soon = p.next === "Today" || p.next === "Tomorrow";
                return (
                  <tr key={p.id} style={{ background: i % 2 ? "var(--surface)" : "color-mix(in oklch, var(--surface-2) 45%, var(--surface))" }}
                    onMouseEnter={(e)=>e.currentTarget.style.background="var(--surface-2)"} onMouseLeave={(e)=>e.currentTarget.style.background=i%2?"var(--surface)":"color-mix(in oklch, var(--surface-2) 45%, var(--surface))"}>
                    <td style={{ padding: "12px 16px" }}>
                      <div style={{ fontSize: 13.5, fontWeight: 650 }}>{p.title}</div>
                      <div className="mono" style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 1 }}>{p.id} · {p.tasks} tasks</div>
                    </td>
                    <td style={{ padding: "12px 16px" }}><FreqPill freq={p.freq} /></td>
                    <td className="hide-md" style={{ padding: "12px 16px" }}>
                      <div style={{ fontSize: 13, fontWeight: 500 }}>{a ? a.name : "—"}</div>
                      <div style={{ fontSize: 11.5, color: "var(--text-faint)", marginTop: 1 }}>{f.name}</div>
                    </td>
                    <td style={{ padding: "12px 16px" }}><span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><Avatar id={p.assignee} size={26} /><span className="hide-sm" style={{ fontSize: 13, fontWeight: 500 }}>{DB.techById(p.assignee).name.split(" ")[0]}</span></span></td>
                    <td style={{ padding: "12px 16px" }}><span className="mono" style={{ fontSize: 12.5, fontWeight: 700, color: soon ? "var(--accent-strong)" : "var(--text-muted)" }}>{p.next}</span></td>
                    <td style={{ padding: "12px 16px" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 9, justifyContent: "flex-end" }}>
                        <span style={{ width: 52, height: 6, borderRadius: 99, background: "var(--surface-3)", overflow: "hidden", display: "block" }}><span style={{ display: "block", height: "100%", width: `${p.compliance}%`, background: `var(${compTok})`, borderRadius: 99 }} /></span>
                        <span className="tnum" style={{ fontSize: 12.5, fontWeight: 700, color: `var(${compTok})`, width: 34, textAlign: "right" }}>{p.compliance}%</span>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>

      {modal && <CreatePMModal onClose={() => setModal(false)} />}
    </div>
  );
};
