
// Inline SVG icons (replacing lucide-react)
const Icon = ({ children, size = 16, strokeWidth = 2, className = '', style = {}, ...rest }) => (
  React.createElement('svg', {
    xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24',
    fill: 'none', stroke: 'currentColor', strokeWidth, strokeLinecap: 'round', strokeLinejoin: 'round',
    className, style, ...rest
  }, children)
);
const P = (d) => React.createElement('path', { d });
const Pl = (points) => React.createElement('polyline', { points });
const Cir = (cx, cy, r) => React.createElement('circle', { cx, cy, r });
const Ln = (x1,y1,x2,y2) => React.createElement('line', { x1,y1,x2,y2 });
const Rec = (props) => React.createElement('rect', props);

const Check = (p) => Icon({ ...p, children: Pl('20 6 9 17 4 12') });
const Trash2 = (p) => Icon({ ...p, children: [Pl('3 6 5 6 21 6'), P('M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2'), Ln(10,11,10,17), Ln(14,11,14,17)] });
const Users = (p) => Icon({ ...p, children: [P('M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2'), Cir(9,7,4), P('M23 21v-2a4 4 0 0 0-3-3.87'), P('M16 3.13a4 4 0 0 1 0 7.75')] });
const Calendar = (p) => Icon({ ...p, children: [Rec({x:3,y:4,width:18,height:18,rx:2,ry:2}), Ln(16,2,16,6), Ln(8,2,8,6), Ln(3,10,21,10)] });
const MessageSquare = (p) => Icon({ ...p, children: P('M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z') });
const ChevronDown = (p) => Icon({ ...p, children: Pl('6 9 12 15 18 9') });
const ChevronUp = (p) => Icon({ ...p, children: Pl('18 15 12 9 6 15') });
const RefreshCw = (p) => Icon({ ...p, children: [Pl('23 4 23 10 17 10'), Pl('1 20 1 14 7 14'), P('M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15')] });
const Sparkles = (p) => Icon({ ...p, children: [P('M12 3l1.9 4.6L18.5 9.5l-4.6 1.9L12 16l-1.9-4.6L5.5 9.5l4.6-1.9z'), P('M19 13l.9 2.2 2.2.9-2.2.9-.9 2.2-.9-2.2-2.2-.9 2.2-.9z')] });

// React hooks shims
const { useState, useEffect, useMemo } = React;


const STORAGE_KEY = 'meeting-schedule-responses-v1';

// 2026年5月のカレンダー（曜日確認済み）
const SCHEDULE = [
  { id: '5-9',  month: 5, day: 9,  dayJa: '土', range: '終日',                      slots: [9,10,11,12,13,14,15,16,17,18,19,20] },
  { id: '5-11', month: 5, day: 11, dayJa: '月', range: '17:00 – 21:00',             slots: [17,18,19,20] },
  { id: '5-12', month: 5, day: 12, dayJa: '火', range: '17:00 – 21:00',             slots: [17,18,19,20] },
  { id: '5-13', month: 5, day: 13, dayJa: '水', range: '17:00 – 21:00',             slots: [17,18,19,20] },
  { id: '5-15', month: 5, day: 15, dayJa: '金', range: '10:00 – 15:00 / 17:00 – 21:00', slots: [10,11,12,13,14,17,18,19,20] },
  { id: '5-18', month: 5, day: 18, dayJa: '月', range: '10:00 – 19:00',             slots: [10,11,12,13,14,15,16,17,18] },
  { id: '5-19', month: 5, day: 19, dayJa: '火', range: '10:00 – 19:00',             slots: [10,11,12,13,14,15,16,17,18] },
  { id: '5-20', month: 5, day: 20, dayJa: '水', range: '17:00 – 21:00',             slots: [17,18,19,20] },
  { id: '5-21', month: 5, day: 21, dayJa: '木', range: '15:00 – 21:00',             slots: [15,16,17,18,19,20] },
  { id: '5-22', month: 5, day: 22, dayJa: '金', range: '終日',                      slots: [9,10,11,12,13,14,15,16,17,18,19,20] },
  { id: '5-23', month: 5, day: 23, dayJa: '土', range: '終日',                      slots: [9,10,11,12,13,14,15,16,17,18,19,20] },
  { id: '5-24', month: 5, day: 24, dayJa: '日', range: '終日',                      slots: [9,10,11,12,13,14,15,16,17,18,19,20] },
];

// 全スロットのフラットなリスト
const ALL_SLOTS = SCHEDULE.flatMap(d => d.slots.map(h => ({ key: `${d.id}_${h}`, dayId: d.id, hour: h })));

const formatHour = (h) => `${h}:00`;
const formatRange = (h) => `${h}:00–${h+1}:00`;

const formatDateTime = (iso) => {
  const d = new Date(iso);
  const m = d.getMonth() + 1;
  const day = d.getDate();
  const hh = String(d.getHours()).padStart(2, '0');
  const mm = String(d.getMinutes()).padStart(2, '0');
  return `${m}/${day} ${hh}:${mm}`;
};

// 共通スタイル変数
const COLORS = {
  cream: '#F4EFE2',
  surface: '#FBF7EE',
  surfaceAlt: '#EFE9D8',
  ink: '#1A1614',
  inkSoft: '#3D3833',
  muted: '#7A7268',
  border: '#D9CFB8',
  borderSoft: '#E5DDC9',
  accent: '#B85440',
  accentDark: '#8E3F2F',
  accentSoft: '#E8C3B5',
};

const SERIF = "'Noto Serif JP', 'Hiragino Mincho ProN', 'Yu Mincho', serif";
const SANS = "'Noto Sans JP', 'Hiragino Kaku Gothic ProN', 'Yu Gothic', sans-serif";

function App() {
  const [tab, setTab] = useState('respond');
  const [name, setName] = useState('');
  const [comment, setComment] = useState('');
  const [selections, setSelections] = useState(() => new Set());
  const [responses, setResponses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [flashMessage, setFlashMessage] = useState(null);
  const [expandedResponse, setExpandedResponse] = useState(null);

  useEffect(() => {
    loadResponses();
    // フォントの読み込み
    const link = document.createElement('link');
    link.href = 'https://fonts.googleapis.com/css2?family=Noto+Serif+JP:wght@400;500;600;700;900&family=Noto+Sans+JP:wght@300;400;500;600;700&display=swap';
    link.rel = 'stylesheet';
    document.head.appendChild(link);
  }, []);

  const loadResponses = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/responses', { cache: 'no-store' });
      if (res.ok) {
        const parsed = await res.json();
        setResponses(Array.isArray(parsed) ? parsed : []);
      }
    } catch (e) {
      // キーが存在しない場合は空配列のまま
      setResponses([]);
    }
    setLoading(false);
  };

  const showFlash = (text, type = 'success') => {
    setFlashMessage({ text, type });
    setTimeout(() => setFlashMessage(null), 2800);
  };

  const toggleSlot = (slotKey) => {
    setSelections(prev => {
      const next = new Set(prev);
      if (next.has(slotKey)) next.delete(slotKey);
      else next.add(slotKey);
      return next;
    });
  };

  const toggleAllForDay = (dayId, slots) => {
    const allKeys = slots.map(h => `${dayId}_${h}`);
    const allSelected = allKeys.every(k => selections.has(k));
    setSelections(prev => {
      const next = new Set(prev);
      if (allSelected) allKeys.forEach(k => next.delete(k));
      else allKeys.forEach(k => next.add(k));
      return next;
    });
  };

  const clearAll = () => {
    setSelections(new Set());
    setName('');
    setComment('');
  };

  const handleSubmit = async () => {
    if (!name.trim()) {
      showFlash('お名前を入力してください', 'error');
      return;
    }
    if (selections.size === 0) {
      showFlash('参加可能な時間を1つ以上選択してください', 'error');
      return;
    }
    setSubmitting(true);
    const newResponse = {
      id: `r_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
      name: name.trim(),
      selections: Array.from(selections),
      comment: comment.trim(),
      submittedAt: new Date().toISOString(),
    };
    const updated = [...responses, newResponse];
    try {
      await fetch('/api/responses', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updated),
      });
      setResponses(updated);
      showFlash('回答を保存しました ✨');
      setSelections(new Set());
      setName('');
      setComment('');
      setTimeout(() => setTab('results'), 1000);
    } catch (e) {
      showFlash('保存に失敗しました。再度お試しください', 'error');
    }
    setSubmitting(false);
  };

  const handleDelete = async (id) => {
    if (!window.confirm('この回答を削除します。よろしいですか？')) return;
    const updated = responses.filter(r => r.id !== id);
    try {
      await fetch('/api/responses', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updated),
      });
      setResponses(updated);
      showFlash('回答を削除しました');
    } catch (e) {
      showFlash('削除に失敗しました', 'error');
    }
  };

  // 集計データ
  const stats = useMemo(() => {
    const totalRespondents = responses.length;
    const slotCounts = {};
    ALL_SLOTS.forEach(s => { slotCounts[s.key] = 0; });
    responses.forEach(r => {
      r.selections.forEach(k => {
        if (slotCounts[k] !== undefined) slotCounts[k]++;
      });
    });
    const ranking = ALL_SLOTS
      .map(s => ({ ...s, count: slotCounts[s.key] }))
      .sort((a, b) => b.count - a.count);
    return { totalRespondents, slotCounts, ranking };
  }, [responses]);

  const getSlotColor = (count, total) => {
    if (total === 0 || count === 0) return { bg: COLORS.surface, text: COLORS.muted };
    const ratio = count / total;
    if (ratio >= 1)    return { bg: COLORS.accent,    text: '#FFF' };
    if (ratio >= 0.75) return { bg: '#C26851',        text: '#FFF' };
    if (ratio >= 0.5)  return { bg: '#D08773',        text: '#FFF' };
    if (ratio >= 0.25) return { bg: '#E0AB97',        text: COLORS.ink };
    return { bg: '#F0D4C5', text: COLORS.ink };
  };

  return (
    <div
      className="min-h-screen w-full"
      style={{
        backgroundColor: COLORS.cream,
        fontFamily: SANS,
        color: COLORS.ink,
        backgroundImage: `radial-gradient(ellipse at top, rgba(184,84,64,0.04) 0%, transparent 50%), radial-gradient(ellipse at bottom right, rgba(184,84,64,0.03) 0%, transparent 60%)`,
      }}
    >
      {/* Flash Message */}
      {flashMessage && (
        <div
          className="fixed top-6 left-1/2 -translate-x-1/2 z-50 px-6 py-3 rounded-full shadow-lg flex items-center gap-2 text-sm font-medium"
          style={{
            backgroundColor: flashMessage.type === 'error' ? '#8E3F2F' : COLORS.ink,
            color: COLORS.cream,
            animation: 'fadeInDown 0.3s ease-out',
          }}
        >
          {flashMessage.type === 'success' && <Check size={16} strokeWidth={2.5} />}
          {flashMessage.text}
        </div>
      )}

      <style>{`
        @keyframes fadeInDown {
          from { opacity: 0; transform: translate(-50%, -10px); }
          to { opacity: 1; transform: translate(-50%, 0); }
        }
        @keyframes pulse {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.5; }
        }
        .slot-btn {
          transition: all 0.15s ease;
        }
        .slot-btn:hover:not(:disabled) {
          transform: translateY(-1px);
        }
      `}</style>

      <div className="max-w-4xl mx-auto px-5 sm:px-8 py-10 sm:py-14">

        {/* Header */}
        <header className="mb-10 sm:mb-14">
          <div className="flex items-center gap-2 mb-4">
            <div
              className="h-px flex-1 max-w-[60px]"
              style={{ backgroundColor: COLORS.accent }}
            />
            <span
              className="text-xs tracking-[0.3em] uppercase font-medium"
              style={{ color: COLORS.accent }}
            >
              Meeting Scheduler
            </span>
            <div
              className="h-px flex-1"
              style={{ backgroundColor: COLORS.border }}
            />
          </div>
          <h1
            className="text-4xl sm:text-5xl font-black leading-tight tracking-tight mb-3"
            style={{ fontFamily: SERIF, color: COLORS.ink }}
          >
            全体会議
            <span
              className="inline-block ml-3 text-2xl sm:text-3xl font-medium"
              style={{ color: COLORS.accent }}
            >
              日程調整
            </span>
          </h1>
          <p
            className="text-sm sm:text-base leading-relaxed"
            style={{ color: COLORS.muted, maxWidth: '600px' }}
          >
            ご自身が参加可能な時間帯を選択してください。各枠は1時間単位です（例：9:00 = 9:00〜10:00）。複数選択できます。
          </p>
        </header>

        {/* Tabs */}
        <div
          className="flex items-center gap-1 mb-8 p-1 rounded-full"
          style={{
            backgroundColor: COLORS.surface,
            border: `1px solid ${COLORS.borderSoft}`,
            width: 'fit-content',
          }}
        >
          <TabButton
            active={tab === 'respond'}
            onClick={() => setTab('respond')}
            icon={<Calendar size={15} strokeWidth={2} />}
            label="回答する"
          />
          <TabButton
            active={tab === 'results'}
            onClick={() => setTab('results')}
            icon={<Users size={15} strokeWidth={2} />}
            label={`結果を見る${responses.length > 0 ? ` (${responses.length})` : ''}`}
          />
        </div>

        {/* Content */}
        {loading ? (
          <div className="text-center py-20" style={{ color: COLORS.muted }}>
            <RefreshCw size={20} className="mx-auto mb-3" style={{ animation: 'spin 1s linear infinite' }} />
            <p className="text-sm">読み込み中...</p>
          </div>
        ) : tab === 'respond' ? (
          <RespondView
            name={name}
            setName={setName}
            comment={comment}
            setComment={setComment}
            selections={selections}
            toggleSlot={toggleSlot}
            toggleAllForDay={toggleAllForDay}
            handleSubmit={handleSubmit}
            clearAll={clearAll}
            submitting={submitting}
          />
        ) : (
          <ResultsView
            responses={responses}
            stats={stats}
            getSlotColor={getSlotColor}
            handleDelete={handleDelete}
            expandedResponse={expandedResponse}
            setExpandedResponse={setExpandedResponse}
            onRefresh={loadResponses}
          />
        )}

        {/* Footer */}
        <footer
          className="mt-16 pt-8 text-center text-xs"
          style={{ borderTop: `1px solid ${COLORS.borderSoft}`, color: COLORS.muted }}
        >
          回答内容は全員に共有されます · データは自動保存されます
        </footer>
      </div>
    </div>
  );
}

// =============== Tab Button ===============

function TabButton({ active, onClick, icon, label }) {
  return (
    <button
      onClick={onClick}
      className="px-4 sm:px-5 py-2 rounded-full text-sm font-medium flex items-center gap-2 transition-all"
      style={{
        backgroundColor: active ? COLORS.ink : 'transparent',
        color: active ? COLORS.cream : COLORS.inkSoft,
      }}
    >
      {icon}
      {label}
    </button>
  );
}

// =============== Respond View ===============

function RespondView({ name, setName, comment, setComment, selections, toggleSlot, toggleAllForDay, handleSubmit, clearAll, submitting }) {
  return (
    <div className="space-y-6">

      {/* Name Input */}
      <div
        className="p-5 sm:p-6 rounded-2xl"
        style={{
          backgroundColor: COLORS.surface,
          border: `1px solid ${COLORS.borderSoft}`,
        }}
      >
        <label className="block">
          <span
            className="text-xs tracking-[0.2em] uppercase font-semibold mb-2 block"
            style={{ color: COLORS.accent }}
          >
            お名前
          </span>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="例：山田 太郎"
            className="w-full text-lg sm:text-xl font-medium bg-transparent border-0 outline-none pb-2"
            style={{
              fontFamily: SERIF,
              color: COLORS.ink,
              borderBottom: `2px solid ${COLORS.border}`,
            }}
            onFocus={(e) => e.target.style.borderBottomColor = COLORS.accent}
            onBlur={(e) => e.target.style.borderBottomColor = COLORS.border}
            maxLength={40}
          />
        </label>
      </div>

      {/* Schedule */}
      <div className="space-y-3">
        {SCHEDULE.map((dayInfo, idx) => (
          <DayCard
            key={dayInfo.id}
            dayInfo={dayInfo}
            selections={selections}
            toggleSlot={toggleSlot}
            toggleAllForDay={toggleAllForDay}
            index={idx}
          />
        ))}
      </div>

      {/* Comment */}
      <div
        className="p-5 sm:p-6 rounded-2xl"
        style={{
          backgroundColor: COLORS.surface,
          border: `1px solid ${COLORS.borderSoft}`,
        }}
      >
        <label className="block">
          <span
            className="text-xs tracking-[0.2em] uppercase font-semibold mb-2 flex items-center gap-2"
            style={{ color: COLORS.accent }}
          >
            <MessageSquare size={12} />
            コメント（任意）
          </span>
          <textarea
            value={comment}
            onChange={(e) => setComment(e.target.value)}
            placeholder="補足事項があれば記入してください"
            rows={3}
            className="w-full text-sm bg-transparent border-0 outline-none resize-none pt-1"
            style={{
              color: COLORS.ink,
              fontFamily: SANS,
            }}
            maxLength={400}
          />
        </label>
      </div>

      {/* Selection Summary & Actions */}
      <div
        className="p-5 sm:p-6 rounded-2xl flex flex-wrap items-center justify-between gap-4"
        style={{
          backgroundColor: COLORS.ink,
          color: COLORS.cream,
        }}
      >
        <div>
          <div className="text-xs tracking-[0.2em] uppercase opacity-60 mb-1">選択中</div>
          <div className="text-2xl font-bold" style={{ fontFamily: SERIF }}>
            {selections.size}
            <span className="text-sm font-normal ml-1 opacity-70">枠</span>
          </div>
        </div>
        <div className="flex gap-2">
          <button
            onClick={clearAll}
            className="px-4 py-2.5 rounded-full text-sm font-medium transition-all"
            style={{
              backgroundColor: 'rgba(244,239,226,0.1)',
              color: COLORS.cream,
            }}
            onMouseEnter={(e) => e.target.style.backgroundColor = 'rgba(244,239,226,0.2)'}
            onMouseLeave={(e) => e.target.style.backgroundColor = 'rgba(244,239,226,0.1)'}
          >
            クリア
          </button>
          <button
            onClick={handleSubmit}
            disabled={submitting}
            className="px-6 py-2.5 rounded-full text-sm font-bold transition-all flex items-center gap-2 disabled:opacity-50"
            style={{
              backgroundColor: COLORS.accent,
              color: '#FFF',
            }}
            onMouseEnter={(e) => !submitting && (e.target.style.backgroundColor = COLORS.accentDark)}
            onMouseLeave={(e) => !submitting && (e.target.style.backgroundColor = COLORS.accent)}
          >
            {submitting ? (
              <>
                <RefreshCw size={14} style={{ animation: 'spin 1s linear infinite' }} />
                送信中...
              </>
            ) : (
              <>
                <Sparkles size={14} />
                回答を送信
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}

// =============== Day Card ===============

function DayCard({ dayInfo, selections, toggleSlot, toggleAllForDay, index }) {
  const allKeys = dayInfo.slots.map(h => `${dayInfo.id}_${h}`);
  const selectedCount = allKeys.filter(k => selections.has(k)).length;
  const allSelected = selectedCount === allKeys.length;
  const isWeekend = dayInfo.dayJa === '土' || dayInfo.dayJa === '日';

  return (
    <div
      className="rounded-2xl overflow-hidden transition-all"
      style={{
        backgroundColor: COLORS.surface,
        border: `1px solid ${selectedCount > 0 ? COLORS.accentSoft : COLORS.borderSoft}`,
      }}
    >
      <div className="p-5 sm:p-6">
        {/* Header Row */}
        <div className="flex items-start justify-between gap-4 mb-4 flex-wrap">
          <div className="flex items-baseline gap-3 flex-wrap">
            <div className="flex items-baseline gap-1.5">
              <span
                className="text-xs font-medium tracking-wider"
                style={{ color: COLORS.muted }}
              >
                5月
              </span>
              <span
                className="text-3xl font-black leading-none"
                style={{ fontFamily: SERIF, color: COLORS.ink }}
              >
                {dayInfo.day}
              </span>
              <span
                className="text-xs font-medium tracking-wider"
                style={{ color: COLORS.muted }}
              >
                日
              </span>
              <span
                className="text-sm font-bold ml-1 px-1.5 rounded"
                style={{
                  color: isWeekend ? '#FFF' : COLORS.inkSoft,
                  backgroundColor: isWeekend ? COLORS.accent : COLORS.surfaceAlt,
                }}
              >
                {dayInfo.dayJa}
              </span>
            </div>
            <span
              className="text-xs font-medium px-2.5 py-1 rounded-full"
              style={{
                backgroundColor: COLORS.surfaceAlt,
                color: COLORS.inkSoft,
              }}
            >
              {dayInfo.range}
            </span>
          </div>
          <button
            onClick={() => toggleAllForDay(dayInfo.id, dayInfo.slots)}
            className="text-xs font-semibold px-3 py-1 rounded-full transition-all"
            style={{
              backgroundColor: allSelected ? COLORS.ink : 'transparent',
              color: allSelected ? COLORS.cream : COLORS.inkSoft,
              border: `1px solid ${allSelected ? COLORS.ink : COLORS.border}`,
            }}
          >
            {allSelected ? '✓ すべて選択中' : 'すべて選択'}
          </button>
        </div>

        {/* Time Slots */}
        <div className="flex flex-wrap gap-2">
          {dayInfo.slots.map((hour) => {
            const key = `${dayInfo.id}_${hour}`;
            const isSelected = selections.has(key);
            return (
              <button
                key={key}
                onClick={() => toggleSlot(key)}
                className="slot-btn px-3 py-2 rounded-lg text-sm font-semibold min-w-[68px]"
                style={{
                  backgroundColor: isSelected ? COLORS.ink : COLORS.cream,
                  color: isSelected ? COLORS.cream : COLORS.inkSoft,
                  border: `1px solid ${isSelected ? COLORS.ink : COLORS.border}`,
                  fontFamily: SANS,
                }}
                title={formatRange(hour)}
              >
                {formatHour(hour)}
              </button>
            );
          })}
        </div>

        {selectedCount > 0 && (
          <div
            className="mt-3 text-xs font-medium flex items-center gap-1.5"
            style={{ color: COLORS.accent }}
          >
            <Check size={12} strokeWidth={2.5} />
            {selectedCount}枠 選択中
          </div>
        )}
      </div>
    </div>
  );
}

// =============== Results View ===============

function ResultsView({ responses, stats, getSlotColor, handleDelete, expandedResponse, setExpandedResponse, onRefresh }) {

  if (responses.length === 0) {
    return (
      <div
        className="text-center py-16 px-6 rounded-2xl"
        style={{
          backgroundColor: COLORS.surface,
          border: `1px dashed ${COLORS.border}`,
        }}
      >
        <Users size={28} style={{ color: COLORS.muted, margin: '0 auto 12px' }} />
        <h3
          className="text-xl font-bold mb-2"
          style={{ fontFamily: SERIF, color: COLORS.ink }}
        >
          まだ回答がありません
        </h3>
        <p className="text-sm" style={{ color: COLORS.muted }}>
          「回答する」タブから最初の回答を入力してください
        </p>
      </div>
    );
  }

  const top5 = stats.ranking.filter(r => r.count > 0).slice(0, 5);

  return (
    <div className="space-y-8">

      {/* Summary */}
      <div
        className="p-6 sm:p-7 rounded-2xl"
        style={{
          backgroundColor: COLORS.ink,
          color: COLORS.cream,
        }}
      >
        <div className="flex items-end justify-between flex-wrap gap-3">
          <div>
            <div className="text-xs tracking-[0.3em] uppercase opacity-60 mb-2">回答者総数</div>
            <div className="flex items-baseline gap-2">
              <span className="text-5xl sm:text-6xl font-black leading-none" style={{ fontFamily: SERIF }}>
                {stats.totalRespondents}
              </span>
              <span className="text-lg opacity-70">名</span>
            </div>
          </div>
          <button
            onClick={onRefresh}
            className="text-xs font-medium px-3 py-2 rounded-full flex items-center gap-2 transition-all"
            style={{
              backgroundColor: 'rgba(244,239,226,0.1)',
              color: COLORS.cream,
            }}
            onMouseEnter={(e) => e.currentTarget.style.backgroundColor = 'rgba(244,239,226,0.2)'}
            onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'rgba(244,239,226,0.1)'}
          >
            <RefreshCw size={12} />
            更新
          </button>
        </div>
      </div>

      {/* Top Times */}
      {top5.length > 0 && (
        <div>
          <h2
            className="text-xs tracking-[0.3em] uppercase font-semibold mb-4 flex items-center gap-2"
            style={{ color: COLORS.accent }}
          >
            <Sparkles size={12} />
            参加可能人数 上位
          </h2>
          <div className="space-y-2">
            {top5.map((slot, idx) => {
              const dayInfo = SCHEDULE.find(d => d.id === slot.dayId);
              const ratio = slot.count / stats.totalRespondents;
              return (
                <div
                  key={slot.key}
                  className="flex items-center gap-4 p-4 rounded-xl"
                  style={{
                    backgroundColor: COLORS.surface,
                    border: `1px solid ${COLORS.borderSoft}`,
                  }}
                >
                  <div
                    className="text-2xl font-black w-8 text-center"
                    style={{
                      fontFamily: SERIF,
                      color: idx === 0 ? COLORS.accent : COLORS.muted,
                    }}
                  >
                    {idx + 1}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-semibold text-sm" style={{ color: COLORS.ink }}>
                      5月{dayInfo.day}日（{dayInfo.dayJa}）{formatRange(slot.hour)}
                    </div>
                    <div
                      className="h-1.5 rounded-full mt-2 overflow-hidden"
                      style={{ backgroundColor: COLORS.surfaceAlt }}
                    >
                      <div
                        className="h-full rounded-full"
                        style={{
                          width: `${ratio * 100}%`,
                          backgroundColor: COLORS.accent,
                          transition: 'width 0.5s ease',
                        }}
                      />
                    </div>
                  </div>
                  <div className="text-right">
                    <div
                      className="text-xl font-bold leading-none"
                      style={{ fontFamily: SERIF, color: COLORS.ink }}
                    >
                      {slot.count}
                      <span className="text-xs font-normal opacity-60 ml-0.5">/{stats.totalRespondents}</span>
                    </div>
                    <div className="text-xs mt-0.5" style={{ color: COLORS.muted }}>
                      {Math.round(ratio * 100)}%
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Heatmap */}
      <div>
        <h2
          className="text-xs tracking-[0.3em] uppercase font-semibold mb-4 flex items-center gap-2"
          style={{ color: COLORS.accent }}
        >
          <Calendar size={12} />
          全体ヒートマップ
        </h2>
        <div
          className="text-xs mb-4 flex items-center gap-3 flex-wrap"
          style={{ color: COLORS.muted }}
        >
          <span>濃さで参加可能な人数を表示：</span>
          <div className="flex items-center gap-1">
            <div className="w-6 h-3 rounded-sm" style={{ backgroundColor: COLORS.surface, border: `1px solid ${COLORS.border}` }} />
            <span className="text-[10px]">0</span>
          </div>
          <div className="flex items-center gap-1">
            <div className="w-6 h-3 rounded-sm" style={{ backgroundColor: '#F0D4C5' }} />
            <div className="w-6 h-3 rounded-sm" style={{ backgroundColor: '#E0AB97' }} />
            <div className="w-6 h-3 rounded-sm" style={{ backgroundColor: '#D08773' }} />
            <div className="w-6 h-3 rounded-sm" style={{ backgroundColor: COLORS.accent }} />
            <span className="text-[10px]">{stats.totalRespondents}名</span>
          </div>
        </div>
        <div className="space-y-2">
          {SCHEDULE.map(dayInfo => (
            <div
              key={dayInfo.id}
              className="p-4 rounded-xl"
              style={{
                backgroundColor: COLORS.surface,
                border: `1px solid ${COLORS.borderSoft}`,
              }}
            >
              <div className="flex items-baseline gap-2 mb-2">
                <span
                  className="text-lg font-bold"
                  style={{ fontFamily: SERIF, color: COLORS.ink }}
                >
                  5/{dayInfo.day}
                </span>
                <span className="text-xs font-medium" style={{ color: COLORS.muted }}>
                  ({dayInfo.dayJa})
                </span>
              </div>
              <div className="flex flex-wrap gap-1.5">
                {dayInfo.slots.map(hour => {
                  const key = `${dayInfo.id}_${hour}`;
                  const count = stats.slotCounts[key];
                  const colors = getSlotColor(count, stats.totalRespondents);
                  const respondentNames = responses
                    .filter(r => r.selections.includes(key))
                    .map(r => r.name);
                  return (
                    <div
                      key={key}
                      className="px-2.5 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1.5 min-w-[60px] justify-between"
                      style={{
                        backgroundColor: colors.bg,
                        color: colors.text,
                        border: count === 0 ? `1px solid ${COLORS.border}` : 'none',
                      }}
                      title={respondentNames.length > 0 ? `${formatRange(hour)}\n${respondentNames.join(', ')}` : `${formatRange(hour)} (0名)`}
                    >
                      <span>{formatHour(hour)}</span>
                      <span className="font-black">{count}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Individual Responses */}
      <div>
        <h2
          className="text-xs tracking-[0.3em] uppercase font-semibold mb-4 flex items-center gap-2"
          style={{ color: COLORS.accent }}
        >
          <Users size={12} />
          個別の回答
        </h2>
        <div className="space-y-2">
          {responses
            .slice()
            .sort((a, b) => new Date(b.submittedAt) - new Date(a.submittedAt))
            .map(response => {
              const isExpanded = expandedResponse === response.id;
              return (
                <div
                  key={response.id}
                  className="rounded-xl overflow-hidden"
                  style={{
                    backgroundColor: COLORS.surface,
                    border: `1px solid ${COLORS.borderSoft}`,
                  }}
                >
                  <div
                    className="flex items-center gap-3 p-4 cursor-pointer"
                    onClick={() => setExpandedResponse(isExpanded ? null : response.id)}
                  >
                    <div
                      className="w-9 h-9 rounded-full flex items-center justify-center text-sm font-bold flex-shrink-0"
                      style={{
                        backgroundColor: COLORS.accent,
                        color: '#FFF',
                        fontFamily: SERIF,
                      }}
                    >
                      {response.name.charAt(0)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="font-bold text-sm" style={{ color: COLORS.ink }}>
                        {response.name}
                      </div>
                      <div className="text-xs flex items-center gap-2 mt-0.5" style={{ color: COLORS.muted }}>
                        <span>{response.selections.length}枠選択</span>
                        <span>·</span>
                        <span>{formatDateTime(response.submittedAt)}</span>
                        {response.comment && (
                          <>
                            <span>·</span>
                            <MessageSquare size={11} />
                          </>
                        )}
                      </div>
                    </div>
                    {isExpanded ? <ChevronUp size={16} style={{ color: COLORS.muted }} /> : <ChevronDown size={16} style={{ color: COLORS.muted }} />}
                  </div>
                  {isExpanded && (
                    <div
                      className="px-4 pb-4 pt-1 space-y-3"
                      style={{ borderTop: `1px solid ${COLORS.borderSoft}` }}
                    >
                      <div>
                        <div
                          className="text-xs font-semibold mb-2 mt-3"
                          style={{ color: COLORS.muted }}
                        >
                          参加可能な時間
                        </div>
                        <div className="space-y-1.5">
                          {SCHEDULE.map(dayInfo => {
                            const selectedHours = dayInfo.slots.filter(h =>
                              response.selections.includes(`${dayInfo.id}_${h}`)
                            );
                            if (selectedHours.length === 0) return null;
                            return (
                              <div key={dayInfo.id} className="flex flex-wrap gap-1.5 items-baseline">
                                <span
                                  className="text-xs font-bold w-16 flex-shrink-0"
                                  style={{ color: COLORS.ink, fontFamily: SERIF }}
                                >
                                  5/{dayInfo.day}({dayInfo.dayJa})
                                </span>
                                {selectedHours.map(h => (
                                  <span
                                    key={h}
                                    className="text-[11px] font-semibold px-2 py-0.5 rounded"
                                    style={{
                                      backgroundColor: COLORS.surfaceAlt,
                                      color: COLORS.inkSoft,
                                    }}
                                  >
                                    {formatHour(h)}
                                  </span>
                                ))}
                              </div>
                            );
                          })}
                        </div>
                      </div>
                      {response.comment && (
                        <div>
                          <div
                            className="text-xs font-semibold mb-1.5"
                            style={{ color: COLORS.muted }}
                          >
                            コメント
                          </div>
                          <div
                            className="text-sm p-3 rounded-lg"
                            style={{
                              backgroundColor: COLORS.cream,
                              color: COLORS.ink,
                              borderLeft: `3px solid ${COLORS.accent}`,
                            }}
                          >
                            {response.comment}
                          </div>
                        </div>
                      )}
                      <button
                        onClick={() => handleDelete(response.id)}
                        className="text-xs font-medium flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-all"
                        style={{
                          color: COLORS.accentDark,
                          border: `1px solid ${COLORS.accentSoft}`,
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.backgroundColor = COLORS.accentDark;
                          e.currentTarget.style.color = '#FFF';
                          e.currentTarget.style.borderColor = COLORS.accentDark;
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.backgroundColor = 'transparent';
                          e.currentTarget.style.color = COLORS.accentDark;
                          e.currentTarget.style.borderColor = COLORS.accentSoft;
                        }}
                      >
                        <Trash2 size={11} />
                        この回答を削除
                      </button>
                    </div>
                  )}
                </div>
              );
            })}
        </div>
      </div>
    </div>
  );
}


// Mount
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(React.createElement(App));
