// FlowSchedule — 活動流程（簡易／詳細切換 + 編輯）
(() => {
const { Panel, Tabs, Badge, Divider, Button, Input, Select } = window.WCATalentGameDesignSystem_377d00;
const { statusTone, statusLabel, statusOptions } = window.WCA_UTIL;
const { Modal, FormRow, ModalActions, EditPencil } = window.WCA_UI;

const TAG = { day: { c: "var(--amber-glow)", t: "☀ 白天" }, dusk: { c: "var(--arcane-blue)", t: "☾ 傍晚" }, night: { c: "var(--role-cpo)", t: "★ 晚上" } };
const TAG_OPTIONS = [{ value: "day", label: "☀ 白天" }, { value: "dusk", label: "☾ 傍晚" }, { value: "night", label: "★ 晚上" }];

function SimpleModal({ step, nextSort, onClose, refresh }) {
  const [f, setF] = React.useState(step || { time: "", title: "", tag: "day" });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const save = async () => {
    if (!f.title.trim()) return alert("請填項目名稱");
    const body = { time: f.time, title: f.title.trim(), tag: f.tag, sort: step ? step.sort : nextSort };
    if (step) await api("PUT", "/api/flow-simple/" + step.id, body);
    else await api("POST", "/api/flow-simple", body);
    await refresh(); onClose();
  };
  const del = step ? async () => { await api("DELETE", "/api/flow-simple/" + step.id); await refresh(); onClose(); } : null;
  return (
    <Modal title={step ? "編輯流程項目" : "新增流程項目"} onClose={onClose}>
      <FormRow cols="1fr 1.6fr 1fr">
        <Input label="時間" value={f.time} onChange={set("time")} placeholder="Day1 09:00" />
        <Input label="項目" value={f.title} onChange={set("title")} />
        <Select label="時段" value={f.tag} onChange={set("tag")} options={TAG_OPTIONS} />
      </FormRow>
      <ModalActions onSave={save} onCancel={onClose} onDelete={del} />
    </Modal>
  );
}

function DetailModal({ step, nextSort, onClose, refresh }) {
  const [f, setF] = React.useState(step
    ? { ...step, gear: step.gear.join("、"), props: step.props.join("、") }
    : { time: "", title: "", owner: "", status: "locked", gear: "", props: "" });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const toList = (s) => s.split(/[、,，]/).map((x) => x.trim()).filter(Boolean);
  const save = async () => {
    if (!f.title.trim()) return alert("請填項目名稱");
    const body = { time: f.time, title: f.title.trim(), owner: f.owner, status: f.status, gear: toList(f.gear), props: toList(f.props), sort: step ? step.sort : nextSort };
    if (step) await api("PUT", "/api/flow-detail/" + step.id, body);
    else await api("POST", "/api/flow-detail", body);
    await refresh(); onClose();
  };
  const del = step ? async () => { await api("DELETE", "/api/flow-detail/" + step.id); await refresh(); onClose(); } : null;
  return (
    <Modal title={step ? "編輯詳細流程" : "新增詳細流程"} onClose={onClose} width={560}>
      <FormRow cols="1fr 1.6fr">
        <Input label="時間" value={f.time} onChange={set("time")} placeholder="09:00–10:00" />
        <Input label="項目" value={f.title} onChange={set("title")} />
      </FormRow>
      <FormRow cols="1fr 1fr">
        <Input label="負責人" value={f.owner} onChange={set("owner")} />
        <Select label="狀態" value={f.status} onChange={set("status")} options={statusOptions} />
      </FormRow>
      <FormRow cols="1fr"><Input label="器材（用「、」分隔）" value={f.gear} onChange={set("gear")} placeholder="投影機、音響、無線麥 ×2" /></FormRow>
      <FormRow cols="1fr"><Input label="道具（用「、」分隔）" value={f.props} onChange={set("props")} placeholder="桌巾 ×6、隊旗 ×6" /></FormRow>
      <ModalActions onSave={save} onCancel={onClose} onDelete={del} />
    </Modal>
  );
}

function SimpleFlow({ data, canEdit, onEdit }) {
  return (
    <div style={{ position: "relative", paddingLeft: 26 }}>
      <span style={{ position: "absolute", left: 7, top: 6, bottom: 6, width: 2, background: "linear-gradient(var(--gold-600),transparent)" }} />
      {data.flowSimple.map((s) => {
        const tg = TAG[s.tag] || TAG.day;
        return (
          <div key={s.id} style={{ position: "relative", marginBottom: 16 }}>
            <span style={{ position: "absolute", left: -26, top: 4, width: 16, height: 16, borderRadius: "50%", background: "var(--navy-900)", border: `2px solid ${tg.c}`, boxShadow: `0 0 8px ${tg.c}` }} />
            <div style={{ display: "flex", alignItems: "baseline", gap: 12 }}>
              <span style={{ fontFamily: "var(--font-pixel)", fontSize: 9, color: "var(--text-muted)", width: 78, flexShrink: 0 }}>{s.time}</span>
              <span style={{ fontFamily: "var(--font-serif)", fontSize: 16, color: "var(--text-primary)" }}>{s.title}</span>
              <span style={{ marginLeft: "auto", fontSize: 11, color: tg.c }}>{tg.t}</span>
              {canEdit && <EditPencil onClick={() => onEdit(s)} />}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function GearList({ title, items, color }) {
  return (
    <div style={{ flex: 1 }}>
      <div style={{ fontFamily: "var(--font-pixel)", fontSize: 8, color, letterSpacing: ".06em", marginBottom: 6 }}>{title}</div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
        {items.map((g, i) => (
          <span key={i} style={{ fontSize: 12, padding: "3px 9px", borderRadius: "var(--radius-sm)", background: "var(--navy-900)", border: "1px solid var(--border-default)", color: "var(--text-secondary)" }}>{g}</span>
        ))}
        {!items.length && <span style={{ fontSize: 12, color: "var(--text-muted)" }}>—</span>}
      </div>
    </div>
  );
}

function DetailFlow({ data, canEdit, onEdit }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {data.flowDetail.map((s) => (
        <div key={s.id} style={{ background: "var(--navy-850)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-md)", padding: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
            <span style={{ fontFamily: "var(--font-pixel)", fontSize: 9, color: "var(--gold-300)" }}>{s.time}</span>
            <span style={{ fontFamily: "var(--font-serif)", fontSize: 16, fontWeight: 700, color: "var(--text-primary)" }}>{s.title}</span>
            <Badge tone={statusTone[s.status]} size="sm" dot style={{ marginLeft: "auto" }}>{statusLabel[s.status]}</Badge>
            {canEdit && <EditPencil onClick={() => onEdit(s)} />}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <span style={{ fontSize: 12, color: "var(--text-muted)" }}>負責人</span>
            <span style={{ fontSize: 13, color: "var(--text-gold)", fontFamily: "var(--font-serif)" }}>{s.owner}</span>
          </div>
          <Divider style={{ marginBottom: 12 }} />
          <div style={{ display: "flex", gap: 24 }}>
            <GearList title="器材 GEAR" items={s.gear} color="var(--tooth-cyan)" />
            <GearList title="道具 PROPS" items={s.props} color="var(--ember-500)" />
          </div>
        </div>
      ))}
    </div>
  );
}

function FlowSchedule({ data, refresh, canEdit }) {
  const [tab, setTab] = React.useState("simple");
  const [modal, setModal] = React.useState(null); // { kind: 'simple'|'detail', step? }
  return (
    <Panel header="活動流程 · Flow" inset="0">
      <div style={{ padding: "14px 18px 0", display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <Tabs value={tab} onChange={setTab} variant="pill" items={[{ id: "simple", label: "簡易流程" }, { id: "detail", label: "詳細流程" }]} />
        {canEdit && (
          <Button size="sm" style={{ marginLeft: "auto" }} onClick={() => setModal({ kind: tab })}>
            ＋ 新增{tab === "simple" ? "流程項目" : "詳細流程"}
          </Button>
        )}
      </div>
      <div style={{ padding: 18 }}>
        {tab === "simple"
          ? <SimpleFlow data={data} canEdit={canEdit} onEdit={(s) => setModal({ kind: "simple", step: s })} />
          : <DetailFlow data={data} canEdit={canEdit} onEdit={(s) => setModal({ kind: "detail", step: s })} />}
      </div>
      {modal && modal.kind === "simple" && (
        <SimpleModal step={modal.step} nextSort={data.flowSimple.length} onClose={() => setModal(null)} refresh={refresh} />
      )}
      {modal && modal.kind === "detail" && (
        <DetailModal step={modal.step} nextSort={data.flowDetail.length} onClose={() => setModal(null)} refresh={refresh} />
      )}
    </Panel>
  );
}
window.FlowSchedule = FlowSchedule;
})();
