/* S3 学生検索（サブ動線） */
const { useState } = React;

function SearchScreen({ nav, onScout }) {
  const { STUDENTS } = window.SV_DATA;
  const { Avatar, Stars, FitBadge, TypeChip, Button, Card, Activity, Pill } = window.SV_UI;
  const Icons = window.SV_Icons;

  // データから選択肢を生成
  const uniq = (arr) => [...new Set(arr)];
  const periodOpts = uniq(STUDENTS.map((s) => s.available)).sort();
  const schoolOpts = uniq(STUDENTS.map((s) => s.school)).sort();
  const labOpts = uniq(STUDENTS.map((s) => s.lab).filter((l) => l && l !== "—")).sort();

  const roles = ["すべて", "獣医学生", "動物看護学生"];
  const ratings = [
    { key: 0, label: "すべて" },
    { key: 3, label: "★3" },
    { key: 2.5, label: "★2.5以上" },
    { key: 2, label: "★2以上" },
  ];
  // ソラタイプ 4軸（全アルファベット）
  const axisDefs = [
    { i: 0, label: "深さ", a: { c: "S", t: "突き詰める" }, b: { c: "G", t: "幅広く" } },
    { i: 1, label: "関わり方", a: { c: "I", t: "個で強い" }, b: { c: "C", t: "組織で動く" } },
    { i: 2, label: "規模志向", a: { c: "V", t: "バリバリ" }, b: { c: "L", t: "安定志向" } },
    { i: 3, label: "役割", a: { c: "T", t: "技術を高める" }, b: { c: "M", t: "まとめ役" } },
  ];
  const sorts = [
    { key: "stars", label: "おすすめ度順" },
    { key: "activity", label: "活性度順" },
  ];
  const ACT_RANK = { high: 3, mid: 2, low: 1 };

  const initial = { role: "すべて", period: "", school: "", lab: "", rating: 0, axis: {}, fitOnly: false, q: "", sort: "stars" };
  const [f, setF] = useState(initial);
  const set = (patch) => setF((prev) => ({ ...prev, ...patch }));
  const toggleAxis = (i, c) => setF((prev) => ({ ...prev, axis: { ...prev.axis, [i]: prev.axis[i] === c ? undefined : c } }));

  const axisActive = Object.values(f.axis).filter(Boolean).length;
  const activeCount =
    (f.role !== "すべて" ? 1 : 0) + (f.period ? 1 : 0) + (f.school ? 1 : 0) + (f.lab ? 1 : 0) +
    (f.rating > 0 ? 1 : 0) + axisActive + (f.fitOnly ? 1 : 0) + (f.q ? 1 : 0);

  const results = STUDENTS
    .filter((s) =>
      (f.role === "すべて" || s.role === f.role) &&
      (!f.period || s.available === f.period) &&
      (!f.school || s.school === f.school) &&
      (!f.lab || s.lab === f.lab) &&
      (s.stars >= f.rating) &&
      [0, 1, 2, 3].every((p) => !f.axis[p] || s.type[p] === f.axis[p]) &&
      (!f.fitOnly || s.fit === "適合") &&
      (!f.q || s.name.includes(f.q) || s.kana.includes(f.q))
    )
    .sort((a, b) =>
      f.sort === "activity"
        ? (ACT_RANK[b.activityLevel] - ACT_RANK[a.activityLevel]) || (b.stars - a.stars)
        : (b.stars - a.stars) || (ACT_RANK[b.activityLevel] - ACT_RANK[a.activityLevel])
    );

  const FilterGroup = ({ label, children }) => (
    <div style={{ marginBottom: 17 }}>
      <div style={{ fontSize: 12, fontWeight: 700, color: "var(--ink-2)", marginBottom: 9 }}>{label}</div>
      {children}
    </div>
  );
  const ChipRow = ({ children }) => <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>{children}</div>;
  const Chip = ({ on, onClick, children }) => (
    <button onClick={onClick} style={{ fontSize: 12.5, fontWeight: 600, padding: "7px 13px", borderRadius: 999, border: on ? "1px solid var(--brand-400)" : "1px solid var(--border-strong)", background: on ? "var(--brand-50)" : "#fff", color: on ? "var(--brand-700)" : "var(--ink-2)", transition: "background .15s, border-color .15s, color .15s" }}>{children}</button>
  );
  const Select = ({ value, onChange, allLabel, options }) => (
    <div style={{ position: "relative" }}>
      <select value={value} onChange={(e) => onChange(e.target.value)}
        style={{ width: "100%", appearance: "none", WebkitAppearance: "none", fontSize: 13, fontWeight: 600, color: value ? "var(--ink)" : "var(--ink-2)", padding: "10px 34px 10px 13px", borderRadius: 10, border: value ? "1px solid var(--brand-400)" : "1px solid var(--border-strong)", background: value ? "var(--brand-50)" : "#fff", cursor: "pointer", outline: "none" }}>
        <option value="">{allLabel}</option>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
      <span style={{ position: "absolute", right: 11, top: "50%", transform: "translateY(-50%)", pointerEvents: "none", color: "var(--ink-3)", display: "flex" }}><Icons.chevronDown size={16} /></span>
    </div>
  );
  // 軸チップ（コード強調＋短いラベル）
  const AxisChip = ({ on, code, text, onClick }) => (
    <button onClick={onClick} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 600, padding: "6px 11px 6px 9px", borderRadius: 999, border: on ? "1px solid var(--brand-400)" : "1px solid var(--border-strong)", background: on ? "var(--brand-50)" : "#fff", color: on ? "var(--brand-700)" : "var(--ink-2)", transition: "background .15s, border-color .15s, color .15s" }}>
      <span className="num" style={{ fontWeight: 800, fontSize: 12.5, letterSpacing: ".04em", color: on ? "var(--brand-700)" : "var(--ink)" }}>{code}</span>
      {text}
    </button>
  );

  return (
    <div>
      <div style={{ marginBottom: 20 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 7, color: "var(--brand-600)", fontSize: 12.5, fontWeight: 700, marginBottom: 7 }}><Icons.search size={15} />学生検索</div>
        <h1 className="disp" style={{ fontSize: 23, fontWeight: 800 }}>条件で絞り込んで詳細へ</h1>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "272px 1fr", gap: 24, alignItems: "start" }}>
        {/* フィルタ */}
        <Card pad={20} style={{ position: "sticky", top: 22 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 7 }}><Icons.filter size={16} /><span className="disp" style={{ fontSize: 14, fontWeight: 700 }}>絞り込み</span></div>
            {activeCount > 0 && (
              <button onClick={() => setF(initial)} style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 12, fontWeight: 600, color: "var(--ink-3)" }}>
                <Icons.x size={13} />クリア
              </button>
            )}
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--surface-3)", borderRadius: 10, padding: "9px 12px", marginBottom: 17 }}>
            <Icons.search size={15} />
            <input value={f.q} onChange={(e) => set({ q: e.target.value })} placeholder="氏名で検索" style={{ border: "none", background: "transparent", fontSize: 13, width: "100%", color: "var(--ink)", outline: "none" }} />
            {f.q && <button onClick={() => set({ q: "" })} style={{ color: "var(--ink-3)", display: "flex" }}><Icons.x size={14} /></button>}
          </div>

          <FilterGroup label="区分">
            <ChipRow>{roles.map((r) => <Chip key={r} on={f.role === r} onClick={() => set({ role: r })}>{r}</Chip>)}</ChipRow>
          </FilterGroup>

          <FilterGroup label="就業可能時期">
            <Select value={f.period} onChange={(v) => set({ period: v })} allLabel="すべての時期" options={periodOpts} />
          </FilterGroup>

          <FilterGroup label="学校">
            <Select value={f.school} onChange={(v) => set({ school: v })} allLabel="すべての学校" options={schoolOpts} />
          </FilterGroup>

          <FilterGroup label="研究室">
            <Select value={f.lab} onChange={(v) => set({ lab: v })} allLabel="すべての研究室" options={labOpts} />
          </FilterGroup>

          <FilterGroup label="おすすめ度">
            <ChipRow>{ratings.map((r) => <Chip key={r.key} on={f.rating === r.key} onClick={() => set({ rating: r.key })}>{r.label}</Chip>)}</ChipRow>
          </FilterGroup>

          <FilterGroup label="働き方の軸（ソラタイプ）">
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {axisDefs.map((ax) => (
                <div key={ax.i}>
                  <div style={{ fontSize: 11, color: "var(--ink-3)", marginBottom: 5 }}>{ax.i + 1}桁目・{ax.label}</div>
                  <div style={{ display: "flex", gap: 7 }}>
                    <AxisChip on={f.axis[ax.i] === ax.a.c} code={ax.a.c} text={ax.a.t} onClick={() => toggleAxis(ax.i, ax.a.c)} />
                    <AxisChip on={f.axis[ax.i] === ax.b.c} code={ax.b.c} text={ax.b.t} onClick={() => toggleAxis(ax.i, ax.b.c)} />
                  </div>
                </div>
              ))}
            </div>
            <div style={{ fontSize: 10.5, color: "var(--ink-3)", marginTop: 9, lineHeight: 1.5 }}>※3桁目（L/V）は単院規模では相性判断に使いません。並べ替えの参考まで。</div>
          </FilterGroup>

          <FilterGroup label="希望動物">
            <Pill icon={Icons.paw} bg="var(--brand-50)" color="var(--brand-700)">犬・猫</Pill>
          </FilterGroup>

          <div style={{ borderTop: "1px solid var(--border)", paddingTop: 16 }}>
            <label style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13, color: "var(--ink)", cursor: "pointer" }}>
              <input type="checkbox" checked={f.fitOnly} onChange={(e) => set({ fitOnly: e.target.checked })} style={{ width: 16, height: 16, accentColor: "var(--brand-600)" }} />
              条件適合のみ表示
            </label>
          </div>
        </Card>

        {/* 結果 */}
        <div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14, gap: 12, flexWrap: "wrap" }}>
            <span style={{ fontSize: 13, color: "var(--ink-2)" }}><b className="num" style={{ color: "var(--ink)", fontSize: 15 }}>{results.length}</b> 名</span>
            <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
              <span style={{ fontSize: 12, color: "var(--ink-3)" }}>並び替え</span>
              {sorts.map((so) => (
                <button key={so.key} onClick={() => set({ sort: so.key })} style={{ fontSize: 12.5, fontWeight: 600, padding: "6px 12px", borderRadius: 999, border: f.sort === so.key ? "1px solid var(--brand-400)" : "1px solid var(--border-strong)", background: f.sort === so.key ? "var(--brand-50)" : "#fff", color: f.sort === so.key ? "var(--brand-700)" : "var(--ink-2)" }}>{so.label}</button>
              ))}
            </div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {results.map((s) => (
              <Card key={s.id} hover pad={16} onClick={() => nav.go("detail", s.id)} style={{ display: "flex", gap: 16, alignItems: "center" }}>
                <Avatar s={s} size={50} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 9, flexWrap: "wrap" }}>
                    <span className="disp" style={{ fontSize: 15.5, fontWeight: 700 }}>{s.name}</span>
                    <FitBadge value={s.fit} size="sm" />
                    <Stars value={s.stars} size={14} />
                  </div>
                  <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 4 }}>{s.role}・{s.year} ／ {s.school} ／ 就業可能 <span className="num" style={{ fontWeight: 600, color: "var(--ink)" }}>{s.available}</span></div>
                  <div style={{ display: "flex", gap: 10, alignItems: "center", marginTop: 9, flexWrap: "wrap" }}>
                    <TypeChip code={s.type} />
                    <Activity level={s.activityLevel} text={s.activity} />
                  </div>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 8, flexShrink: 0 }}>
                  <Button variant="primary" size="sm" icon={Icons.send} onClick={(e) => { e.stopPropagation(); onScout(s.id); }}>スカウト</Button>
                  <Button variant="ghost" size="sm" iconRight={Icons.arrowRight} onClick={(e) => { e.stopPropagation(); nav.go("detail", s.id); }}>詳細</Button>
                </div>
              </Card>
            ))}
            {results.length === 0 && (
              <div style={{ textAlign: "center", padding: 50, color: "var(--ink-3)", fontSize: 13 }}>
                該当する学生がいません。条件をゆるめてください。
                <div style={{ marginTop: 14 }}><Button variant="ghost" size="sm" icon={Icons.x} onClick={() => setF(initial)}>条件をクリア</Button></div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.SV_Search = SearchScreen;
