// screens/revisit.jsx — 재방문 관리 / 알림톡 자동 발송

function RevisitScreen({ setRoute }) {
  const Icons = window.Icons;
  const [filter, setFilter] = React.useState("all");
  const [selected, setSelected] = React.useState("rv-1");

  const stages = [
    { v: "all", l: "전체", count: REVISITS.length },
    { v: "pending", l: "예약대기", count: 2 },
    { v: "sent", l: "발송완료", count: 1 },
    { v: "booked", l: "예약완료", count: 1 },
    { v: "scheduled", l: "발송예정", count: 1 },
  ];

  const sel = REVISITS.find(r => r.id === selected) || REVISITS[0];

  // Mock retention chart data (28 days)
  const RETAIN_DATA = [82, 79, 80, 78, 77, 76, 78, 80, 82, 81, 79, 78, 76, 73, 71, 72, 74, 77, 80, 83, 85, 86, 84, 82, 80, 78, 77, 76];

  return (
    <div className="page fade-up">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">08 · 재방문 관리 · 알림톡 자동 발송</div>
          <h1 className="page-title">개인화 재방문 큐 — <span className="num">{REVISITS.length}</span>명 대기</h1>
          <p className="page-sub">
            시술 후 효과 감소 시점·패키지 잔여·방문 주기를 기반으로 AI가 재방문 적기를 산출하고 알림톡·카톡 채널을 통해 맞춤 메시지를 자동 발송합니다.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn btn-soft btn-sm"><Icons.Refresh size={13} /> 큐 새로고침</button>
          <button className="btn btn-primary"><Icons.Send size={13} /> 일괄 발송 (6명)</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="grid grid-4" style={{ marginBottom: 18 }}>
        <Card pad="lg"><Stat label="당월 발송" value="284" delta="+24" sub="목표 320건" /></Card>
        <Card pad="lg"><Stat label="응답률" value="38.6%" delta="+4.2pp" sub="알림톡 평균 22%" /></Card>
        <Card pad="lg"><Stat label="예약 전환" value="142건" delta="+18" sub="전환율 50%" /></Card>
        <Card pad="lg"><Stat label="예상 매출 기여" value="₩186M" delta="+12M" deltaSign="up" sub="당월 누적" /></Card>
      </div>

      <div className="grid grid-12">
        {/* LEFT — Queue list */}
        <div className="col-7">
          <Card pad="md">
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
              <Tabs tabs={stages.map(s => ({ v: s.v, l: `${s.l} ${s.count}` }))} value={filter} onChange={setFilter} />
              <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--ink-3)" }}>
                <Icons.Filter size={13} /> 정렬: AI 우선순위
              </div>
            </div>
            <table className="table">
              <thead>
                <tr>
                  <th>환자 / 이슈</th>
                  <th style={{ width: 110 }}>마지막 방문</th>
                  <th style={{ width: 130 }}>제안 일정</th>
                  <th style={{ width: 80 }}>신뢰도</th>
                  <th style={{ width: 110 }}>상태</th>
                </tr>
              </thead>
              <tbody>
                {REVISITS.map(r => (
                  <tr key={r.id} onClick={() => setSelected(r.id)} style={{ cursor: "pointer", background: selected === r.id ? "var(--bg-subtle)" : undefined }}>
                    <td>
                      <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                        <Avatar initials={r.patient.slice(0,1)} size={32} color="var(--ink-2)" />
                        <div>
                          <div style={{ fontWeight: 600, color: "var(--ink-1)" }}>{r.patient}</div>
                          <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{r.concern}</div>
                        </div>
                      </div>
                    </td>
                    <td><span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{r.lastVisit}</span></td>
                    <td>
                      <div className="num" style={{ fontSize: 13, fontWeight: 600 }}>{r.suggestedDate.split(" ")[0].slice(5)}</div>
                      <div style={{ fontSize: 11, color: "var(--ink-4)" }}>{r.suggestedDate.split(" ")[1]}</div>
                    </td>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        <div style={{ width: 36, height: 6, background: "var(--bg-subtle)", borderRadius: 999, overflow: "hidden" }}>
                          <div style={{ width: `${r.confidence}%`, height: "100%", background: r.confidence >= 85 ? "var(--good)" : "var(--watch)" }}></div>
                        </div>
                        <span className="num" style={{ fontSize: 11.5, fontWeight: 600 }}>{r.confidence}</span>
                      </div>
                    </td>
                    <td>
                      <Pill tone={
                        r.status === "예약완료" ? "good" :
                        r.status === "예약대기" ? "watch" :
                        r.status === "발송완료" ? "info" :
                        r.status === "콜백예약" ? "skin" : "outline"
                      } dot>{r.status}</Pill>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>

          {/* Retention chart */}
          <Card pad="lg" style={{ marginTop: 14 }} title="30일 효과 유지 추세 (AI 예측)">
            <div style={{ display: "flex", alignItems: "center", gap: 18, marginBottom: 8 }}>
              <div>
                <div className="num" style={{ fontSize: 22, fontWeight: 700 }}>76%</div>
                <div style={{ fontSize: 11, color: "var(--ink-3)" }}>현재 평균 효과 유지율</div>
              </div>
              <div>
                <div className="num" style={{ fontSize: 22, fontWeight: 700, color: "var(--watch)" }}>D-12</div>
                <div style={{ fontSize: 11, color: "var(--ink-3)" }}>효과 감소 임계 도달 평균</div>
              </div>
              <div style={{ marginLeft: "auto" }}>
                <LineChart data={RETAIN_DATA} w={420} h={140} color="var(--phase-tint)" yUnit="%" />
              </div>
            </div>
          </Card>
        </div>

        {/* RIGHT — Message preview */}
        <div className="col-5" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Card pad="lg">
            <div className="card-title-row">
              <h3 className="card-title"><span className="dot"></span>알림톡 메시지 (자동 생성)</h3>
              <Pill tone="info"><Icons.Sparkle size={11} /> {sel.channel}</Pill>
            </div>

            {/* Phone preview */}
            <div style={{
              background: "var(--bg-subtle)", borderRadius: 18, padding: 14,
              maxWidth: 360, margin: "0 auto",
            }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: "var(--ink-4)", padding: "4px 8px 10px" }}>
                <span className="mono">9:41</span>
                <span style={{ fontWeight: 600 }}>알림톡 · 안양 강남점</span>
                <span></span>
              </div>
              <div style={{ background: "#FDEB6E", color: "var(--ink-1)", padding: "10px 14px", borderRadius: 14, fontSize: 12.5, lineHeight: 1.6 }}>
                <div style={{ fontWeight: 700, marginBottom: 6 }}>[안양피부과] {sel.patient.split(" ")[0]} 고객님께</div>
                지난 {sel.lastVisit} 진행하신 시술 효과가 잘 유지되고 있는 시점입니다.<br /><br />
                AI 분석 결과, <strong>{sel.suggestedDate}</strong>경 다음 회차({sel.nextTreatment})를 진행하시면 누적 효과가 가장 잘 안정화됩니다.<br /><br />
                패키지 잔여 회차는 <strong>2회</strong>입니다.
              </div>
              <div style={{ background: "#FFF", padding: "10px 14px", borderRadius: 14, marginTop: 6, fontSize: 12 }}>
                <div style={{ color: "var(--data-blue)", fontWeight: 600 }}>예약 가능 시간대</div>
                <div style={{ marginTop: 6, display: "flex", flexWrap: "wrap", gap: 6 }}>
                  {["수 14:00", "수 16:30", "금 11:00", "토 10:30"].map(t =>
                    <span key={t} style={{ padding: "4px 8px", background: "var(--bg-subtle)", borderRadius: 999, fontSize: 11 }}>{t}</span>)}
                </div>
              </div>
              <div style={{ display: "flex", gap: 6, marginTop: 8 }}>
                <button className="btn btn-soft btn-sm" style={{ flex: 1, fontSize: 11 }}>예약하기</button>
                <button className="btn btn-ghost btn-sm" style={{ flex: 1, fontSize: 11 }}>다른 일정</button>
              </div>
            </div>

            <div className="divider" />

            <div style={{ display: "flex", gap: 8 }}>
              <button className="btn btn-soft btn-sm" style={{ flex: 1 }}><Icons.Edit size={12} /> 메시지 편집</button>
              <button className="btn btn-soft btn-sm" style={{ flex: 1 }}><Icons.Sparkle size={12} /> 재생성</button>
              <button className="btn btn-primary btn-sm" style={{ flex: 1 }}><Icons.Send size={12} /> 발송</button>
            </div>
          </Card>

          <Card pad="md" title="발송 채널 성과 (당월)">
            {[
              { ch: "알림톡 (카카오)", sent: 184, conv: 0.48, color: "#FDEB6E" },
              { ch: "카톡 채널", sent: 62, conv: 0.61, color: "#FDD835" },
              { ch: "SMS (LMS)", sent: 28, conv: 0.21, color: "#E0E0E0" },
              { ch: "실장 직접 콜", sent: 10, conv: 0.83, color: "var(--data-blue)" },
            ].map((c, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 0", borderBottom: i < 3 ? "1px dashed var(--line-hair)" : "0" }}>
                <span style={{ width: 8, height: 8, borderRadius: "50%", background: c.color }}></span>
                <span style={{ flex: 1, fontSize: 13, fontWeight: 500 }}>{c.ch}</span>
                <span style={{ fontSize: 12, color: "var(--ink-3)" }}>{c.sent}건</span>
                <span style={{ width: 70, textAlign: "right" }}>
                  <span className="num" style={{ fontWeight: 600 }}>{Math.round(c.conv * 100)}%</span>
                  <span style={{ fontSize: 10.5, color: "var(--ink-4)", marginLeft: 4 }}>전환</span>
                </span>
              </div>
            ))}
          </Card>
        </div>
      </div>
    </div>
  );
}

window.RevisitScreen = RevisitScreen;
