/* S6 病院実習カレンダー */
const { useState } = React;

function CalendarScreen({ nav }) {
  const { SLOTS, SLOT_KINDS, studentById } = window.SV_DATA;
  const { Button, Card, Note, Pill } = window.SV_UI;
  const Icons = window.SV_Icons;

  const [slots, setSlots] = useState(() => [...SLOTS]);
  const [sel, setSel] = useState(18);
  const [adding, setAdding] = useState(false);
  const [form, setForm] = useState({
    kind: (SLOT_KINDS && SLOT_KINDS[0]) || "1day病院実習",
    date: "27",
    capacity: "1",
    time: "10:00 – 16:00",
    staff: "",
  });

  const WD = ["日", "月", "火", "水", "木", "金", "土"];
  const firstOffset = 1; // 2026/6/1 は月曜
  const daysInMonth = 30;
  const today = 15;
  const slotByDate = (d) => slots.find((x) => x.date === d);
  const KIND_COLOR = { done: "var(--fit)", booked: "var(--brand-600)", open: "var(--ink-3)" };

  const cells = [];
  for (let i = 0; i < firstOffset; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);

  const selSlot = slotByDate(sel);
  const setF = (patch) => setForm((p) => ({ ...p, ...patch }));

  const addSlot = () => {
    const d = parseInt(form.date);
    if (!d || d < 1 || d > 30) return;
    const newSlot = {
      date: d,
      kind: "open",
      label: form.kind,
      time: form.time,
      capacity: parseInt(form.capacity) || 1,
      booked: null,
      staff: form.staff || "担当者未定",
    };
    setSlots((prev) => {
      const filtered = prev.filter((x) => x.date !== d);
      return [...filtered, newSlot].sort((a, b) => a.date - b.date);
    });
    setSel(d);
    setAdding(false);
  };

  return (
    <div>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 20, gap: 16, flexWrap: "wrap" }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 7, color: "var(--brand-600)", fontSize: 12.5, fontWeight: 700, marginBottom: 7 }}><Icons.calendar size={15} />病院実習カレンダー</div>
          <h1 className="disp" style={{ fontSize: 23, fontWeight: 800 }}>実習枠を置けば、学生が予約します</h1>
          <p style={{ fontSize: 13.5, color: "var(--ink-2)", marginTop: 7, lineHeight: 1.6, maxWidth: 640 }}>枠ごとに<b>呼称</b>を選べます（1day病院実習／見学／実習(2日)／インターン）。学生にはその呼称で表示。予約時に持ち物・注意事項を自動送信します。</p>
        </div>
        <Button variant="primary" icon={Icons.plus} onClick={() => setAdding(true)}>枠を追加</Button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 22, alignItems: "start" }}>
        {/* カレンダー */}
        <Card pad={20}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
            <button style={{ color: "var(--ink-3)", padding: 6 }}><Icons.arrowLeft size={18} /></button>
            <div className="disp" style={{ fontSize: 18, fontWeight: 800 }}>2026年 <span style={{ color: "var(--brand-700)" }}>6月</span></div>
            <button style={{ color: "var(--ink-3)", padding: 6 }}><Icons.arrowRight size={18} /></button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 6 }}>
            {WD.map((w, i) => <div key={w} style={{ textAlign: "center", fontSize: 11.5, fontWeight: 700, color: i === 0 ? "var(--miss)" : i === 6 ? "var(--brand-600)" : "var(--ink-3)", padding: "4px 0" }}>{w}</div>)}
            {cells.map((d, i) => {
              if (!d) return <div key={i} />;
              const slot = slotByDate(d);
              const isSel = d === sel;
              const isToday = d === today;
              return (
                <button key={i} onClick={() => { if (slot) setSel(d); }} style={{
                  minHeight: 76, borderRadius: 10, padding: "6px 7px", textAlign: "left", position: "relative",
                  border: isSel ? "1.5px solid var(--brand-500)" : "1px solid var(--border)",
                  background: isSel ? "var(--brand-50)" : slot ? "var(--surface)" : "var(--surface-2)",
                  cursor: slot ? "pointer" : "default", transition: "border-color .15s, background .15s",
                }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <span className="num" style={{ fontSize: 13, fontWeight: 700, color: i % 7 === 0 ? "var(--miss)" : "var(--ink)" }}>{d}</span>
                    {isToday && <span style={{ fontSize: 9, fontWeight: 700, color: "#fff", background: "var(--brand-600)", borderRadius: 4, padding: "1px 4px" }}>今日</span>}
                  </div>
                  {slot && (
                    <div style={{ marginTop: 5, fontSize: 10, fontWeight: 700, color: "#fff", background: KIND_COLOR[slot.kind], borderRadius: 5, padding: "2px 5px", lineHeight: 1.3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                      {slot.label}
                    </div>
                  )}
                  {slot && slot.booked && <div style={{ marginTop: 3, fontSize: 9.5, color: "var(--ink-2)" }}>{slot.booked}</div>}
                  {slot && !slot.booked && <div style={{ marginTop: 3, fontSize: 9.5, color: "var(--brand-600)" }}>空き{slot.capacity}</div>}
                </button>
              );
            })}
          </div>
          <div style={{ display: "flex", gap: 16, marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--border)", fontSize: 11.5, color: "var(--ink-2)" }}>
            {[["完了", "var(--fit)"], ["予約済み", "var(--brand-600)"], ["募集中", "var(--ink-3)"]].map(([t, c]) => (
              <span key={t} style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: c }} />{t}</span>
            ))}
          </div>
        </Card>

        {/* 右：選択枠の詳細 / 追加フォーム */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16, position: "sticky", top: 22 }}>
          {adding ? (
            <Card pad={20}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
                <h3 className="disp" style={{ fontSize: 16, fontWeight: 700 }}>実習枠を追加</h3>
                <button onClick={() => setAdding(false)} style={{ color: "var(--ink-3)" }}><Icons.x size={18} /></button>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
                <CalField label="呼称（学生に表示）">
                  <select value={form.kind} onChange={(e) => setF({ kind: e.target.value })} style={selStyle}>
                    {(SLOT_KINDS || ["1day病院実習", "見学", "実習(2日)", "インターン"]).map((k) => <option key={k}>{k}</option>)}
                  </select>
                </CalField>
                <div style={{ display: "flex", gap: 10 }}>
                  <CalField label="日付（6月）" style={{ flex: 1 }}>
                    <input value={form.date} onChange={(e) => setF({ date: e.target.value })} placeholder="例: 27" style={inpStyle} />
                  </CalField>
                  <CalField label="定員" style={{ width: 80 }}>
                    <input value={form.capacity} onChange={(e) => setF({ capacity: e.target.value })} style={inpStyle} />
                  </CalField>
                </div>
                <CalField label="時間">
                  <input value={form.time} onChange={(e) => setF({ time: e.target.value })} style={inpStyle} />
                </CalField>
                <CalField label="当日担当">
                  <input value={form.staff} onChange={(e) => setF({ staff: e.target.value })} placeholder="例：院長" style={inpStyle} />
                </CalField>
                <Note tone="brand" icon={Icons.sparkle}>予約時に<b>持ち物・注意事項</b>をチャットへ自動投稿します。</Note>
                <Button variant="primary" icon={Icons.check} full onClick={addSlot}>この枠を追加</Button>
              </div>
            </Card>
          ) : selSlot ? (
            <Card pad={20}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                <span className="num" style={{ fontSize: 26, fontWeight: 800, color: "var(--brand-700)", whiteSpace: "nowrap" }}>6/{selSlot.date}</span>
                <Pill bg="var(--brand-50)" color="var(--brand-700)">{selSlot.label}</Pill>
              </div>
              <div style={{ fontSize: 13, color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 6, marginTop: 6 }}><Icons.clock size={15} />{selSlot.time}</div>

              <div style={{ marginTop: 16, padding: "13px 15px", borderRadius: 12, background: selSlot.booked ? "var(--brand-50)" : "var(--surface-3)", border: selSlot.booked ? "1px solid var(--brand-100)" : "1px solid var(--border)" }}>
                {selSlot.booked ? (
                  <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                    <span style={{ color: "var(--brand-600)" }}><Icons.user size={20} /></span>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 700 }}>{selSlot.booked} さんが予約</div>
                      <div style={{ fontSize: 11.5, color: "var(--ink-2)", marginTop: 2 }}>当日担当：{selSlot.staff}</div>
                    </div>
                  </div>
                ) : (
                  <div style={{ fontSize: 13, color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 8 }}><Icons.clock size={16} />募集中（空き {selSlot.capacity}）・学生の予約待ち</div>
                )}
              </div>

              {/* 当日チェックリスト */}
              <div style={{ marginTop: 16 }}>
                <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)", marginBottom: 9 }}>当日チェックリスト</div>
                {[["担当者の割り当て", true], ["見学ルート・症例の準備", true], ["持ち物・注意事項の自動送信", true], ["簡易評価メモの準備", false]].map(([t, done]) => (
                  <div key={t} style={{ display: "flex", alignItems: "center", gap: 9, padding: "7px 0", fontSize: 13, color: done ? "var(--ink)" : "var(--ink-2)" }}>
                    <span style={{ color: done ? "var(--fit)" : "var(--ink-3)" }}>{done ? <Icons.checkCircle size={18} /> : <Icons.clock size={18} />}</span>{t}
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 12, display: "flex", gap: 8 }}>
                {selSlot.booked && <Button variant="ghost" size="sm" full icon={Icons.chat} onClick={() => nav.go("messages", studentById(selSlot.kind === "done" ? "sato" : "takahashi")?.id)}>チャットを開く</Button>}
                <Button variant="plain" size="sm" full icon={Icons.trash} onClick={() => { setSlots((p) => p.filter((x) => x.date !== sel)); setSel(null); }}>枠を削除</Button>
              </div>
            </Card>
          ) : (
            <Card pad={20}>
              <div style={{ textAlign: "center", padding: "20px 0", color: "var(--ink-3)", fontSize: 13, lineHeight: 1.7 }}>
                カレンダーの日付をクリックして<br/>詳細を確認できます
              </div>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

const CalField = ({ label, children, style }) => (
  <label style={{ display: "block", ...style }}>
    <span style={{ fontSize: 12, fontWeight: 700, color: "var(--ink-2)", display: "block", marginBottom: 6 }}>{label}</span>
    {children}
  </label>
);
const inpStyle = { width: "100%", padding: "10px 12px", borderRadius: 10, border: "1px solid var(--border-strong)", fontSize: 13.5, fontFamily: "var(--sans)", color: "var(--ink)", outline: "none" };
const selStyle = { ...inpStyle, appearance: "auto", cursor: "pointer" };

window.SV_Calendar = CalendarScreen;
