// Naviyell — Screens A-13 through A-18 — INTERACTIVE

// ═══════════════════════════════════════════════════════════════════
// A-13 Session record
// ═══════════════════════════════════════════════════════════════════
function A13Record() {
  const nav = useNav();
  const { state, patch } = useAppState();
  const [added, setAdded] = React.useState(false);

  const addAll = () => {
    const items = [
      { desc: '転職エージェント1社のサイトを見てみる', due: '〜 3/28（金）' },
      { desc: '今の仕事で「続けたい3つ」を書き出す', due: '〜 3/29（土）' },
      { desc: '元同僚1人と話す機会を作る', due: '〜 4/2（水）' },
    ];
    const actions = state.actions || MOCK_ACTIONS;
    const news = items.map((it, i) => ({
      id: 'rec-' + Date.now() + '-' + i,
      desc: it.desc,
      due: it.due,
      source: '葉月さんとのセッション',
      catColor: A.catMind,
      cat: '心のアンカー',
      done: false,
    }));
    patch({ actions: [...news, ...actions], showAddedToast: true });
    setAdded(true);
    setTimeout(() => nav.go('tracker', { replace: true }), 800);
  };

  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <ACTopBar leading={<ACBack />} title='セッション記録' />
      <div style={{ flex: 1, overflow: 'auto', padding: '8px 20px 20px' }} className='ac-scroll'>
        <div style={{ padding: '12px 0' }}>
          <div style={{ fontSize: 12, color: A.ink500 }}>2025年3月26日（水） 14:00 〜 14:48</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>
            <ACAvatar size={28} name='葉' color={A.catMind} />
            <span style={{ fontSize: 14, fontWeight: 600 }}>葉月 凛</span>
            <ACBadge tone='success' style={{ marginLeft: 'auto' }}>
              完了
            </ACBadge>
          </div>
        </div>

        <Section title='セッションメモ'>
          <div style={{ background: A.white, borderRadius: 14, padding: 16, border: `1px solid ${A.ink100}` }}>
            <p style={{ margin: 0, fontSize: 14, lineHeight: 1.8, color: A.ink700 }}>
              現在の仕事への違和感の正体について、これまでの経歴を一緒に整理しました。続けたい部分は「人と関わる仕事」「企画する楽しさ」、手放したい部分は「数値の責任」「長時間労働」と明確に。転職を急ぐのではなく、まずは情報収集と小さな対話から始める方針で合意しました。
            </p>
          </div>
        </Section>

        <Section title='アドバイス'>
          <div style={{ background: A.white, borderRadius: 14, padding: 16, border: `1px solid ${A.ink100}` }}>
            {[
              '「踏み切る勇気」を待つよりも、判断材料を増やす行動を先に。',
              '大きな決断の前に、信頼できる他者との対話を3回挟む習慣を持つ。',
              '今の職場で「やりがい」と感じる瞬間を週1回、書き留めてみる。',
            ].map((line, i) => (
              <div
                key={i}
                style={{
                  display: 'flex',
                  gap: 12,
                  padding: '10px 0',
                  borderBottom: i < 2 ? `1px solid ${A.ink100}` : 'none',
                }}>
                <span className='ac-display' style={{ fontSize: 18, fontWeight: 600, color: A.gold500, lineHeight: 1.2 }}>
                  {i + 1}
                </span>
                <span style={{ fontSize: 13.5, color: A.ink700, lineHeight: 1.7, flex: 1 }}>{line}</span>
              </div>
            ))}
          </div>
        </Section>

        <Section title='次のアクション'>
          <div style={{ background: A.white, borderRadius: 14, padding: 4, border: `1px solid ${A.ink100}` }}>
            {[
              { d: '転職エージェント1社のサイトを見てみる', dt: '〜 3/28（金）' },
              { d: '今の仕事で「続けたい3つ」を書き出す', dt: '〜 3/29（土）' },
              { d: '元同僚1人と話す機会を作る', dt: '〜 4/2（水）' },
            ].map((a, i, arr) => (
              <div
                key={i}
                style={{
                  display: 'flex',
                  alignItems: 'flex-start',
                  gap: 12,
                  padding: '14px 12px',
                  borderBottom: i < arr.length - 1 ? `1px solid ${A.ink100}` : 'none',
                }}>
                <div
                  style={{
                    width: 22,
                    height: 22,
                    borderRadius: 6,
                    flexShrink: 0,
                    marginTop: 1,
                    border: `1.5px solid ${added ? A.success : A.ink300}`,
                    background: added ? A.success : 'transparent',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    transition: 'all 0.2s',
                  }}>
                  {added && (
                    <svg width='12' height='12' viewBox='0 0 12 12'>
                      <path d='M2 6l3 3 5-6' stroke={A.white} strokeWidth='2' fill='none' strokeLinecap='round' strokeLinejoin='round' />
                    </svg>
                  )}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, color: A.ink900, lineHeight: 1.5 }}>{a.d}</div>
                  <div style={{ fontSize: 11, color: A.gold600, marginTop: 4, fontWeight: 600 }}>期日：{a.dt}</div>
                </div>
              </div>
            ))}
          </div>
        </Section>
      </div>
      <ACStickyCTA>
        <ACButton size='lg' onClick={addAll} disabled={added}>
          {added ? '✓ 追加しました' : '行動トラッカーに追加する'}
        </ACButton>
        <button
          onClick={() => nav.go('messages')}
          style={{
            width: '100%',
            marginTop: 8,
            height: 40,
            border: 'none',
            background: 'transparent',
            color: A.gold600,
            fontSize: 13,
            fontWeight: 500,
            cursor: 'pointer',
            fontFamily: 'inherit',
          }}>
          メッセージで質問する
        </button>
      </ACStickyCTA>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// A-14 Action tracker
// ═══════════════════════════════════════════════════════════════════
function A14Tracker() {
  const { state, patch } = useAppState();
  const actions = state.actions || MOCK_ACTIONS;
  const completed = actions.filter((a) => a.done).length;
  const total = actions.length;
  const rate = total > 0 ? Math.round((completed / total) * 100) : 0;
  const grouped = {};
  actions.forEach((a) => {
    (grouped[a.cat] = grouped[a.cat] || { color: a.catColor, items: [] }).items.push(a);
  });

  const toggle = (id) => {
    patch({ actions: actions.map((a) => (a.id === id ? { ...a, done: !a.done } : a)) });
  };

  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div
        style={{
          paddingTop: 56,
          padding: '56px 20px 0',
          display: 'flex',
          alignItems: 'baseline',
          justifyContent: 'space-between',
        }}>
        <h1 className='ac-serif' style={{ margin: 0, fontSize: 24, fontWeight: 600 }}>
          行動トラッカー
        </h1>
        <button
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 4,
            padding: '6px 12px',
            background: A.white,
            border: `1px solid ${A.ink100}`,
            borderRadius: 18,
            fontSize: 12,
            fontWeight: 600,
            color: A.ink700,
            cursor: 'pointer',
            fontFamily: 'inherit',
          }}>
          今週
          <svg width='10' height='10' viewBox='0 0 10 10'>
            <path d='M2 4l3 3 3-3' stroke={A.ink500} strokeWidth='1.5' fill='none' strokeLinecap='round' />
          </svg>
        </button>
      </div>

      <div style={{ padding: '20px 20px 0' }}>
        <div
          style={{
            background: A.white,
            borderRadius: 16,
            padding: '20px 20px',
            border: `1px solid ${A.ink100}`,
            display: 'flex',
            alignItems: 'center',
            gap: 20,
          }}>
          <ProgressRing value={rate} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, color: A.ink500, letterSpacing: 1, fontWeight: 600 }}>EXECUTION RATE</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 4 }}>
              <span className='ac-display' style={{ fontSize: 34, fontWeight: 600, color: A.ink900, lineHeight: 1 }}>
                {rate}
              </span>
              <span style={{ fontSize: 16, color: A.ink500, fontWeight: 500 }}>%</span>
            </div>
            <div style={{ fontSize: 12, color: A.ink500, marginTop: 4 }}>
              {completed} / {total} 件 完了
            </div>
          </div>
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '20px 20px 20px' }} className='ac-scroll'>
        {Object.entries(grouped).map(([cat, g]) => (
          <div key={cat} style={{ marginBottom: 20 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10, padding: '0 4px' }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: g.color }} />
              <span style={{ fontSize: 12, fontWeight: 600, color: A.ink700, letterSpacing: 0.5 }}>{cat}</span>
            </div>
            <div style={{ background: A.white, borderRadius: 14, border: `1px solid ${A.ink100}` }}>
              {g.items.map((a, i) => (
                <button
                  key={a.id}
                  onClick={() => toggle(a.id)}
                  style={{
                    width: '100%',
                    display: 'flex',
                    alignItems: 'flex-start',
                    gap: 12,
                    padding: '14px 14px',
                    borderBottom: i < g.items.length - 1 ? `1px solid ${A.ink100}` : 'none',
                    background: 'transparent',
                    border: 'none',
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                    textAlign: 'left',
                  }}>
                  <div
                    style={{
                      width: 22,
                      height: 22,
                      borderRadius: 6,
                      flexShrink: 0,
                      marginTop: 1,
                      border: `1.5px solid ${a.done ? A.success : A.ink300}`,
                      background: a.done ? A.success : 'transparent',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      transition: 'all 0.15s',
                    }}>
                    {a.done && (
                      <svg width='12' height='12' viewBox='0 0 12 12'>
                        <path d='M2 6l3 3 5-6' stroke={A.white} strokeWidth='2' fill='none' strokeLinecap='round' strokeLinejoin='round' />
                      </svg>
                    )}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div
                      style={{
                        fontSize: 14,
                        color: a.done ? A.ink500 : A.ink900,
                        textDecoration: a.done ? 'line-through' : 'none',
                        lineHeight: 1.5,
                      }}>
                      {a.desc}
                    </div>
                    <div style={{ fontSize: 11, color: A.ink500, marginTop: 4 }}>
                      {a.due} · {a.source}
                    </div>
                  </div>
                </button>
              ))}
            </div>
          </div>
        ))}

        <ACButton variant='secondary' size='md'>
          振り返りメモを書く
        </ACButton>
      </div>

      <ACTabBar active='tracker' />
      <Toast />
    </div>
  );
}

function ProgressRing({ value }) {
  const r = 32,
    c = 2 * Math.PI * r;
  const offset = c - (c * value) / 100;
  return (
    <div style={{ position: 'relative', width: 80, height: 80 }}>
      <svg width='80' height='80' viewBox='0 0 80 80' style={{ transform: 'rotate(-90deg)' }}>
        <circle cx='40' cy='40' r={r} stroke={A.ink100} strokeWidth='6' fill='none' />
        <circle
          cx='40'
          cy='40'
          r={r}
          stroke={A.gold500}
          strokeWidth='6'
          fill='none'
          strokeLinecap='round'
          strokeDasharray={c}
          strokeDashoffset={offset}
          style={{ transition: 'stroke-dashoffset 0.4s ease' }}
        />
      </svg>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// A-15 Messages
// ═══════════════════════════════════════════════════════════════════
function A15Messages() {
  const nav = useNav();
  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ paddingTop: 56, padding: '56px 20px 0' }}>
        <h1 className='ac-serif' style={{ margin: 0, fontSize: 24, fontWeight: 600 }}>
          メッセージ
        </h1>
      </div>
      <div style={{ flex: 1, overflow: 'auto', padding: '16px 0 0' }} className='ac-scroll'>
        {MOCK_THREADS.map((th, i) => {
          const a = MOCK_ANCHORS.find((x) => x.id === th.anchorId);
          return (
            <button
              key={th.id}
              onClick={() => nav.go('session')}
              style={{
                width: '100%',
                display: 'flex',
                gap: 12,
                padding: '14px 20px',
                borderBottom: i < MOCK_THREADS.length - 1 ? `1px solid ${A.ink100}` : 'none',
                background: 'transparent',
                border: 'none',
                cursor: 'pointer',
                fontFamily: 'inherit',
                textAlign: 'left',
              }}>
              <ACAvatar size={48} name={a.name.charAt(0)} color={a.color} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <span style={{ fontSize: 14, fontWeight: 600, color: A.ink900 }}>{a.name}</span>
                  <span style={{ fontSize: 11, color: A.ink500 }}>{th.time}</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, marginTop: 4 }}>
                  <span
                    style={{
                      flex: 1,
                      fontSize: 13,
                      color: th.unread ? A.ink900 : A.ink500,
                      lineHeight: 1.5,
                      fontWeight: th.unread ? 500 : 400,
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      display: '-webkit-box',
                      WebkitLineClamp: 2,
                      WebkitBoxOrient: 'vertical',
                    }}>
                    {th.preview}
                  </span>
                  {th.unread && (
                    <span
                      style={{
                        width: 8,
                        height: 8,
                        borderRadius: '50%',
                        background: A.gold500,
                        flexShrink: 0,
                        marginTop: 6,
                      }}
                    />
                  )}
                </div>
              </div>
            </button>
          );
        })}
      </div>
      <ACTabBar active='messages' />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// A-16 Payment history
// ═══════════════════════════════════════════════════════════════════
function A16Payments() {
  const { state, patch } = useAppState();
  const tab = state.paymentTab;
  const tabs = ['すべて', '完了', 'キャンセル'];
  const filtered = MOCK_PAYMENTS.filter((p) => {
    if (tab === 0) return true;
    if (tab === 1) return p.status === '完了';
    if (tab === 2) return p.status === 'キャンセル';
    return true;
  });
  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <ACTopBar leading={<ACBack />} title='お支払い履歴' />
      <div style={{ display: 'flex', gap: 8, padding: '12px 20px', borderBottom: `1px solid ${A.ink100}` }}>
        {tabs.map((c, i) => (
          <ACPill key={c} active={i === tab} onClick={() => patch({ paymentTab: i })}>
            {c}
          </ACPill>
        ))}
      </div>
      <div style={{ flex: 1, overflow: 'auto', padding: '16px 20px 20px' }} className='ac-scroll'>
        {filtered.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '40px 0', color: A.ink500, fontSize: 13 }}>該当する履歴はありません</div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {filtered.map((p) => (
              <div
                key={p.id}
                style={{
                  background: A.white,
                  borderRadius: 14,
                  padding: 14,
                  border: `1px solid ${A.ink100}`,
                  animation: 'ac-fade-in 200ms ease both',
                }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <span style={{ fontSize: 11, color: A.ink500 }}>{p.date}</span>
                  <ACBadge tone={p.status === '完了' ? 'success' : 'neutral'}>{p.status}</ACBadge>
                </div>
                <div className='ac-serif' style={{ fontSize: 14, fontWeight: 600, color: A.ink900, marginTop: 6, lineHeight: 1.5 }}>
                  {p.title}
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 8 }}>
                  <span style={{ fontSize: 12, color: A.ink500 }}>{p.anchor}</span>
                  <span className='ac-display' style={{ fontSize: 18, fontWeight: 600, color: A.ink900 }}>
                    ¥{p.amount.toLocaleString()}
                  </span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// A-17 Notifications
// ═══════════════════════════════════════════════════════════════════
function A17Notifications() {
  const nav = useNav();
  const [notifs, setNotifs] = React.useState(MOCK_NOTIFICATIONS);
  const markRead = (id) => {
    setNotifs((n) => n.map((x) => (x.id === id ? { ...x, unread: false } : x)));
    if (id === 'n1') nav.go('status');
    else if (id === 'n2') nav.go('record');
    else if (id === 'n3') nav.go('messages');
  };
  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <ACTopBar
        leading={<ACBack />}
        title='お知らせ'
        trailing={
          <button
            onClick={() => setNotifs((n) => n.map((x) => ({ ...x, unread: false })))}
            style={{
              background: 'transparent',
              border: 'none',
              color: A.gold600,
              fontSize: 12,
              fontWeight: 600,
              cursor: 'pointer',
              fontFamily: 'inherit',
              paddingRight: 12,
            }}>
            すべて既読
          </button>
        }
      />
      <div style={{ flex: 1, overflow: 'auto' }} className='ac-scroll'>
        {notifs.map((n) => (
          <button
            key={n.id}
            onClick={() => markRead(n.id)}
            style={{
              width: '100%',
              display: 'flex',
              gap: 12,
              padding: '14px 20px',
              background: n.unread ? `${A.gold100}55` : 'transparent',
              borderTop: 'none',
              borderRight: 'none',
              borderBottom: `1px solid ${A.ink100}`,
              borderLeft: n.unread ? `3px solid ${A.gold500}` : '3px solid transparent',
              cursor: 'pointer',
              fontFamily: 'inherit',
              textAlign: 'left',
              transition: 'background 0.15s',
            }}>
            <NotifIcon type={n.icon} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: A.ink900 }}>{n.title}</div>
              <div style={{ fontSize: 12, color: A.ink500, marginTop: 4, lineHeight: 1.6 }}>{n.body}</div>
              <div style={{ fontSize: 10, color: A.ink500, marginTop: 6 }}>{n.time}</div>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

function NotifIcon({ type }) {
  const map = {
    cal: { bg: A.gold100, fg: A.gold600, path: <path d='M5 5h14v14H5zM5 9h14M9 3v4M15 3v4' strokeLinecap='round' /> },
    bell: {
      bg: '#FBEFD9',
      fg: A.warning,
      path: <path d='M6 14V10a6 6 0 1 1 12 0v4l2 3H4l2-3zM10 19a2 2 0 0 0 4 0' strokeLinecap='round' strokeLinejoin='round' />,
    },
    msg: {
      bg: '#E3E5F0',
      fg: A.ink700,
      path: <path d='M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-7l-4 3.5V17H6a2 2 0 0 1-2-2V6z' strokeLinejoin='round' />,
    },
    star: {
      bg: A.gold100,
      fg: A.gold600,
      path: <path d='M12 2l3 7 7 .8-5.3 5 1.3 7L12 18l-6 3.8 1.3-7L2 9.8 9 9z' strokeLinejoin='round' />,
    },
  };
  const m = map[type];
  return (
    <div
      style={{
        width: 36,
        height: 36,
        borderRadius: 10,
        background: m.bg,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexShrink: 0,
      }}>
      <svg width='18' height='18' viewBox='0 0 24 24' fill='none' stroke={m.fg} strokeWidth='1.8'>
        {m.path}
      </svg>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// A-18 My page
// ═══════════════════════════════════════════════════════════════════
function A18MyPage() {
  const nav = useNav();
  const { state, patch } = useAppState();
  const user = state.currentUser;
  const isGuest = user?.user_metadata?.is_guest === true;
  const userId = user?.id || 'default';
  const avatarUrl = state.avatarUrl || localStorage.getItem('naviyell_avatar_' + userId) || '';
  const email = state.pendingEmail || localStorage.getItem('naviyell_email') || user?.email || '';
  const displayName = state.displayName ||
    user?.user_metadata?.public_username || user?.user_metadata?.full_name || user?.user_metadata?.name || user?.email?.split('@')[0] || '';
  
  // Born type from app state (fall back to mock default)
  const bornType = state.bornType || bornTypeFromBirthday(state.birthMonth || 7, state.birthDay || 15);
  const el = ELEMENTS[bornType] || ELEMENTS.wind;

  const handleCreateAccount = () => {
    // Switch to signup tab before navigating
    patch({ auth: { ...state.auth, tab: 'signup' } });
    nav.go('login', { replace: true });
  };
  
  const accountItems = isGuest 
    ? [{ label: 'アカウントを作成', action: handleCreateAccount, highlight: true }]
    : [{ label: 'プロフィール編集', go: 'profile-edit' }, { label: 'メールアドレス変更', go: 'email-edit' }, { label: 'パスワード変更', go: 'password-edit' }];
  
  const groups = [
    {
      title: 'アカウント',
      items: accountItems,
    },
    { title: 'アプリ設定', items: [{ label: '通知設定', go: 'notifications' }, { label: '表示設定' }] },
    {
      title: '履歴',
      items: [
        { label: 'お支払い履歴', go: 'payments' },
        { label: 'セッション履歴', go: 'record' },
      ],
    },
    {
      title: 'サポート',
      items: [{ label: 'ヘルプ', go: 'help' }, { label: 'お問い合わせ', go: 'contact' }, { label: '利用規約', go: 'terms-of-service' }, { label: 'プライバシーポリシー', go: 'privacy-policy' }],
    },
    {
      title: 'アカウント管理',
      items: [
        { label: 'ログアウト', danger: true, action: () => DB.signOut().catch(console.error) },
        { label: '退会', danger: true },
      ],
    },
  ];
  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, overflow: 'auto', paddingTop: 56 }} className='ac-scroll'>
        <div style={{ padding: '8px 20px 20px' }}>
          <div
            style={{
              background: A.white,
              borderRadius: 16,
              padding: 18,
              border: `1px solid ${A.ink100}`,
              display: 'flex',
              alignItems: 'center',
              gap: 14,
            }}>
            {avatarUrl ? (
              <div
                style={{
                  width: 56,
                  height: 56,
                  borderRadius: '50%',
                  background: `center/cover url(${avatarUrl})`,
                  border: `2px solid ${A.ink100}`,
                  flexShrink: 0,
                }}
              />
            ) : (
              <ACAvatar size={56} name={displayName.charAt(0)} color={A.ink700} />
            )}
            <div style={{ flex: 1 }}>
              <div className='ac-serif' style={{ fontSize: 18, fontWeight: 600, color: A.ink900 }}>
                {displayName}
              </div>
              <div
                style={{
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 4,
                  marginTop: 6,
                  padding: '3px 10px',
                  background: el.color + '22',
                  borderRadius: 12,
                }}>
                <svg width='10' height='10' viewBox='0 0 24 24' fill='none' stroke={el.accent} strokeWidth='2'>
                  <path d='M3 8a4 4 0 0 1 8 0c0 4-4 8-4 12M21 16a4 4 0 0 0-8 0c0-4 4-8 4-12' strokeLinecap='round' />
                </svg>
                <span style={{ fontSize: 11, fontWeight: 600, color: el.accent }}>{el.label}のサイン</span>
              </div>
              <div style={{ fontSize: 11, color: A.ink500, marginTop: 6 }}>会員登録：{(() => {
                const d = user?.created_at ? new Date(user.created_at) : null;
                return d ? `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日` : '-';
              })()}</div>
            </div>
          </div>
        </div>

        {groups.map((g) => (
          <div key={g.title} style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: A.ink500, letterSpacing: 0.5, padding: '0 24px 8px' }}>{g.title}</div>
            <div
              style={{
                background: A.white,
                borderTop: `1px solid ${A.ink100}`,
                borderBottom: `1px solid ${A.ink100}`,
              }}>
              {g.items.map((it, i) => (
                <button
                  key={it.label}
                  onClick={() => (it.action ? it.action() : it.go && nav.go(it.go, (it.go === 'terms-of-service' || it.go === 'privacy-policy') ? {} : { replace: true }))}
                  style={{
                    width: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    padding: '14px 20px',
                    borderTop: 'none',
                    borderRight: 'none',
                    borderBottom: i < g.items.length - 1 ? `1px solid ${A.ink100}` : 'none',
                    borderLeft: 'none',
                    background: it.highlight ? `${A.gold100}55` : 'transparent',
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                    textAlign: 'left',
                    fontWeight: it.highlight ? 600 : 400,
                    color: it.highlight ? A.gold700 : (it.danger ? A.danger : A.ink900),
                  }}>
                  <span style={{ fontSize: 14 }}>{it.label}</span>
                  {it.highlight ? (
                    <svg width='16' height='16' viewBox='0 0 24 24' fill='none' stroke={A.gold600} strokeWidth='2'>
                      <path d='M12 5v14M5 12h14' strokeLinecap='round' />
                    </svg>
                  ) : (
                    <svg width='8' height='14' viewBox='0 0 8 14'>
                      <path d='M1 1l6 6-6 6' stroke={A.ink300} strokeWidth='1.5' fill='none' strokeLinecap='round' strokeLinejoin='round' />
                    </svg>
                  )}
                </button>
              ))}
            </div>
          </div>
        ))}
        <div style={{ height: 20 }} />
      </div>
      <ACTabBar active='mypage' />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// A-22 Terms of Service
// ═══════════════════════════════════════════════════════════════════
function A22TermsOfService() {
  const nav = useNav();
  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <ACTopBar leading={<ACBack />} title='利用規約' />
      <div style={{ flex: 1, overflow: 'auto', padding: '20px 24px 40px' }} className='ac-scroll'>
        <div style={{ maxWidth: 600, margin: '0 auto' }}>
          <h1 className='ac-serif' style={{ fontSize: 24, fontWeight: 600, color: A.ink900, marginBottom: 24, textAlign: 'center' }}>
            利用規約
          </h1>
          
          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第1条（適用）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              本利用規約（以下「本規約」）は、NAVIYELL（以下「当社」）が提供する占い・カウンセリングプラットフォームサービス（以下「本サービス」）の利用条件を定めるものです。ユーザーの皆様（以下「ユーザー」）は、本規約に同意の上、本サービスをご利用ください。
            </p>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第2条（利用登録）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              本サービスの利用を希望する方は、当社の定める方法により利用登録を行うものとします。当社は、利用登録の申請者に以下の事由があると判断した場合、登録を拒否することがあります。
            </p>
            <ul style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, paddingLeft: 20, marginBottom: 16 }}>
              <li>本規約に違反するおそれがあると当社が判断した場合</li>
              <li>虚偽の事項を申告した場合</li>
              <li>過去に本サービスの利用を停止されたことがある場合</li>
              <li>その他、当社が登録を適当でないと判断した場合</li>
            </ul>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第3条（禁止事項）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              ユーザーは、本サービスの利用にあたり、以下の行為をしてはならないものとします。
            </p>
            <ul style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, paddingLeft: 20, marginBottom: 16 }}>
              <li>法令または公序良俗に違反する行為</li>
              <li>当社または第三者の知的財産権を侵害する行為</li>
              <li>当社または第三者の名誉・信用を毀損する行為</li>
              <li>本サービスのネットワークまたはシステム等に過度な負荷をかける行為</li>
              <li>本サービスの運営を妨害するおそれのある行為</li>
              <li>他のユーザーに対する嫌がらせや迷惑行為</li>
              <li>虚偽の情報を提供する行為</li>
              <li>商業目的での本サービスの利用（当社が認めた場合を除く）</li>
            </ul>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第4条（本サービスの提供の停止等）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              当社は、以下のいずれかの事由があると判断した場合、ユーザーに事前に通知することなく本サービスの全部または一部の提供を停止または中断することができるものとします。
            </p>
            <ul style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, paddingLeft: 20, marginBottom: 16 }}>
              <li>本サービスにかかるシステムの保守点検または更新を行う場合</li>
              <li>地震、落雷、火災、停電または天災地変などの不可抗力により本サービスの提供が困難になった場合</li>
              <li>コンピュータまたは通信回線等が事故により停止した場合</li>
              <li>その他、当社が本サービスの提供が困難と判断した場合</li>
            </ul>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第5条（免責事項）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              当社は、本サービスに事実上または法律上の瑕疵（安全性、信頼性、正確性、完全性、有効性、特定の目的への適合性、セキュリティなどに関する欠陥、エラーやバグ、権利侵害などを含みます）がないことを保証するものではありません。
            </p>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              当社は、本サービスがユーザーの特定の目的に適合すること、期待する機能・正確性・有用性を有すること、不具合が生じないこと、および本サービスが継続的に提供されることについて保証するものではありません。
            </p>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第6条（利用規約の変更）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              当社は、必要と判断した場合には、ユーザーに通知することなく本規約を変更することができるものとします。変更後の本規約は、本サービスに掲載された時点から効力を生じるものとします。
            </p>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第7条（準拠法・裁判管轄）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              本規約の解釈にあたっては、日本法を準拠法とします。本サービスに関して紛争が生じた場合には、当社の本店所在地を管轄する裁判所を第一審の専属的合意管轄裁判所とします。
            </p>
          </div>

          <div style={{ textAlign: 'center', marginTop: 40, paddingTop: 24, borderTop: `1px solid ${A.ink100}` }}>
            <p style={{ fontSize: 12, color: A.ink500 }}>最終更新日：2025年1月1日</p>
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// A-23 Privacy Policy
// ═══════════════════════════════════════════════════════════════════
function A23PrivacyPolicy() {
  const nav = useNav();
  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <ACTopBar leading={<ACBack />} title='プライバシーポリシー' />
      <div style={{ flex: 1, overflow: 'auto', padding: '20px 24px 40px' }} className='ac-scroll'>
        <div style={{ maxWidth: 600, margin: '0 auto' }}>
          <h1 className='ac-serif' style={{ fontSize: 24, fontWeight: 600, color: A.ink900, marginBottom: 24, textAlign: 'center' }}>
            プライバシーポリシー
          </h1>
          
          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第1条（個人情報の定義）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              本プライバシーポリシーにおいて、個人情報とは、個人情報保護法に定義される「個人情報」を指し、生存する個人に関する情報であって、当該情報に含まれる氏名、生年月日、住所、電話番号、メールアドレスその他の記述等により特定の個人を識別できるものをいいます。
            </p>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第2条（個人情報の収集）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              当社は、以下の場合に個人情報を収集することがあります。
            </p>
            <ul style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, paddingLeft: 20, marginBottom: 16 }}>
              <li>ユーザーが本サービスに登録する際</li>
              <li>ユーザーが本サービスを利用する際</li>
              <li>ユーザーがお問い合わせをする際</li>
              <li>本サービスの改善のため、自動的に情報を収集する場合</li>
            </ul>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第3条（個人情報の利用目的）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              当社は、収集した個人情報を以下の目的で利用します。
            </p>
            <ul style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, paddingLeft: 20, marginBottom: 16 }}>
              <li>本サービスの提供・運営のため</li>
              <li>ユーザー認証のため</li>
              <li>本サービスに関するお知らせを送信するため</li>
              <li>ユーザーからのお問い合わせに回答するため</li>
              <li>本サービスの改善・新機能の開発のため</li>
              <li>利用規約に違反したユーザーの特定のため</li>
            </ul>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第4条（個人情報の第三者提供）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              当社は、以下の場合を除き、ユーザーの同意なく第三者に個人情報を提供することはありません。
            </p>
            <ul style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, paddingLeft: 20, marginBottom: 16 }}>
              <li>法令に基づく場合</li>
              <li>人の生命、身体または財産の保護のために必要がある場合</li>
              <li>公衆衛生の向上または児童の健全な育成の推進のために特に必要がある場合</li>
              <li>国の機関もしくは地方公共団体またはその委託を受けた者が法令の定める事務を遂行することに対して協力する必要がある場合</li>
            </ul>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第5条（個人情報の安全管理）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              当社は、個人情報の漏洩、滅失、き損等を防止するため、適切な安全管理措置を講じます。また、個人情報を取り扱う従業者や委託先に対して、必要かつ適切な監督を行います。
            </p>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第6条（Cookieの使用）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              本サービスでは、ユーザー体験の向上のためCookieを使用することがあります。Cookieの使用を希望しない場合は、ブラウザの設定でCookieを無効にすることができますが、本サービスの一部機能が利用できなくなる場合があります。
            </p>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第7条（個人情報の開示・訂正・削除）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              ユーザーは、当社に対して自身の個人情報の開示、訂正、追加、削除を請求することができます。請求は、本サービス内の設定画面またはお問い合わせフォームから行うことができます。
            </p>
          </div>

          <div style={{ marginBottom: 32 }}>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: A.ink900, marginBottom: 12 }}>第8条（プライバシーポリシーの変更）</h2>
            <p style={{ fontSize: 14, lineHeight: 1.8, color: A.ink700, marginBottom: 16 }}>
              当社は、必要に応じて本プライバシーポリシーを変更することがあります。変更後のプライバシーポリシーは、本サービスに掲載された時点から効力を生じるものとします。
            </p>
          </div>

          <div style={{ textAlign: 'center', marginTop: 40, paddingTop: 24, borderTop: `1px solid ${A.ink100}` }}>
            <p style={{ fontSize: 12, color: A.ink500 }}>最終更新日：2025年1月1日</p>
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// A-24 Help / FAQ
// ═══════════════════════════════════════════════════════════════════
function A24Help() {
  const nav = useNav();
  const [expanded, setExpanded] = React.useState(null);

  const faqs = [
    {
      q: 'NAVIYELLとは何ですか？',
      a: 'NAVIYELLは、占いとカウンセリングを組み合わせた自己理解サポートプラットフォームです。あなたの内面に潜む「心のアンカー」を解き放ち、本来の自分らしさを見つけるお手伝いをします。',
    },
    {
      q: '予約からセッションまでの流れを教えてください',
      a: '1. 占い師（アンカー）一覧からお好きな方を選択\n2. カレンダーからご希望の日時を選択\n3. セッション料金をお支払い\n4. セッション当日にオンラインでお会いします',
    },
    {
      q: '支払い方法を教えてください',
      a: 'クレジットカード（Visa、Mastercard、American Express）および各種電子決済サービスをご利用いただけます。お支払いはセッション予約時に行います。',
    },
    {
      q: 'キャンセル・変更はいつまでに連絡すればよいですか？',
      a: 'セッション開始の24時間前までにキャンセル・変更のご連絡をお願いしております。それ以降のキャンセルについては、キャンセル料が発生する場合がございます。',
    },
    {
      q: 'セッションはオンラインで行われますか？',
      a: 'はい、現在のところすべてのセッションはオンライン（ビデオ通話）で実施しております。セッション開始前に、招待リンクをお送りします。',
    },
    {
      q: '個人情報は安全に管理されますか？',
      a: '当社は、業界標準のセキュリティ対策を講じ、お客様の個人情報を適切に管理しております。詳細はプライバシーポリシーをご確認ください。',
    },
    {
      q: '退会したい場合はどうすればよいですか？',
      a: 'マイページの「アカウント管理」セクションから退会手続きを行うことができます。退会後も、法令に定められた期間は一定の情報を保持する場合がございます。',
    },
    {
      q: '不具合や質問がある場合はどうすればよいですか？',
      a: 'マイページの「お問い合わせ」より、サポートチームまでご連絡ください。通常2営業日以内にご返信いたします。',
    },
  ];

  const toggle = (i) => {
    setExpanded(expanded === i ? null : i);
  };

  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <ACTopBar
        leading={
          <button
            onClick={() => nav.back('mypage')}
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: 40,
              height: 40,
              background: 'transparent',
              border: 'none',
              cursor: 'pointer',
              padding: 0,
            }}>
            <svg width='24' height='24' viewBox='0 0 24 24' fill='none' stroke={A.ink900} strokeWidth='2' strokeLinecap='round' strokeLinejoin='round'>
              <path d='M15 18l-6-6 6-6' />
            </svg>
          </button>
        }
        title='ヘルプ'
      />
      <div style={{ flex: 1, overflow: 'auto', padding: '20px 20px 40px' }} className='ac-scroll'>
        <div style={{ maxWidth: 600, margin: '0 auto' }}>
          <div style={{ marginBottom: 24, textAlign: 'center' }}>
            <h1 className='ac-serif' style={{ fontSize: 24, fontWeight: 600, color: A.ink900, margin: '0 0 8px' }}>
              よくあるご質問
            </h1>
            <p style={{ fontSize: 13, color: A.ink500, margin: 0 }}>
              不明な点がございましたら、お気軽にお問い合わせください
            </p>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {faqs.map((item, i) => {
              const isOpen = expanded === i;
              return (
                <div
                  key={i}
                  style={{
                    background: A.white,
                    borderRadius: 14,
                    border: `1px solid ${A.ink100}`,
                    overflow: 'hidden',
                    transition: 'box-shadow 0.2s',
                    boxShadow: isOpen ? `0 2px 8px ${A.ink100}` : 'none',
                  }}>
                  <button
                    onClick={() => toggle(i)}
                    style={{
                      width: '100%',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      padding: '16px 18px',
                      background: 'transparent',
                      border: 'none',
                      cursor: 'pointer',
                      fontFamily: 'inherit',
                      textAlign: 'left',
                      gap: 12,
                    }}>
                    <span style={{ fontSize: 14, fontWeight: 600, color: A.ink900, lineHeight: 1.5, flex: 1 }}>
                      {item.q}
                    </span>
                    <svg
                      width='16'
                      height='16'
                      viewBox='0 0 16 16'
                      style={{
                        flexShrink: 0,
                        transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                        transition: 'transform 0.2s ease',
                      }}>
                      <path d='M4 6l4 4 4-4' stroke={A.ink500} strokeWidth='1.8' fill='none' strokeLinecap='round' strokeLinejoin='round' />
                    </svg>
                  </button>
                  <div
                    style={{
                      maxHeight: isOpen ? 300 : 0,
                      overflow: 'hidden',
                      transition: 'max-height 0.25s ease',
                    }}>
                    <div
                      style={{
                        padding: '0 18px 18px',
                        fontSize: 13.5,
                        color: A.ink700,
                        lineHeight: 1.8,
                        borderTop: `1px solid ${A.ink100}`,
                        marginTop: 0,
                        paddingTop: 14,
                        whiteSpace: 'pre-line',
                      }}>
                      {item.a}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          <div
            style={{
              marginTop: 32,
              padding: '20px',
              background: A.white,
              borderRadius: 14,
              border: `1px solid ${A.ink100}`,
              textAlign: 'center',
            }}>
            <p style={{ fontSize: 14, fontWeight: 600, color: A.ink900, margin: '0 0 8px' }}>
              お問い合わせ
            </p>
            <p style={{ fontSize: 13, color: A.ink500, margin: '0 0 16px', lineHeight: 1.6 }}>
              上記で解決しない場合は、サポートチームまでご連絡ください
            </p>
            <ACButton variant='secondary' size='md' onClick={() => nav.go('contact')}>
              お問い合わせフォームへ
            </ACButton>
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// A-25 Contact / Inquiry Form
// ═══════════════════════════════════════════════════════════════════
function A25Contact() {
  const nav = useNav();
  const { state } = useAppState();
  const user = state.currentUser;
  const [formData, setFormData] = React.useState({
    name: user?.user_metadata?.full_name || user?.email?.split('@')[0] || '',
    email: user?.email || '',
    subject: '',
    message: '',
  });
  const [submitted, setSubmitted] = React.useState(false);
  const [errors, setErrors] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);

  const validate = () => {
    const newErrors = {};
    if (!formData.name.trim()) newErrors.name = 'お名前を入力してください';
    if (!formData.email.trim()) newErrors.email = 'メールアドレスを入力してください';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) newErrors.email = '有効なメールアドレスを入力してください';
    if (!formData.subject.trim()) newErrors.subject = '件名を入力してください';
    if (!formData.message.trim()) newErrors.message = 'お問い合わせ内容を入力してください';
    else if (formData.message.trim().length < 10) newErrors.message = '10文字以上で入力してください';
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    // Prevent any default form behavior
    if (e) e.preventDefault();
    
    console.log('Submit button clicked!')
    console.log('Form data:', formData)
    console.log('Errors:', errors)
    console.log('Submitted state:', submitted)
    
    if (!validate()) {
      console.log('Validation failed')
      return
    }
    
    console.log('Validation passed, submitting...')
    setSubmitting(true)
    
    try {
      // Send via Formspree
      const formspreeUrl = 'https://formspree.io/f/xlgybrll'
      
      const formDataToSend = new FormData()
      formDataToSend.append('name', formData.name)
      formDataToSend.append('email', formData.email)
      formDataToSend.append('subject', formData.subject)
      formDataToSend.append('message', formData.message)
      
      const formspreeResponse = await fetch(formspreeUrl, {
        method: 'POST',
        body: formDataToSend,
        headers: {
          'Accept': 'application/json'
        }
      })
      
      if (!formspreeResponse.ok) {
        const errorData = await formspreeResponse.json()
        throw new Error(errorData.message || 'Failed to send via Formspree')
      }
      
      console.log('✅ Form submitted successfully via Formspree')
      setSubmitted(true)
      setSubmitting(false)
      // No auto-redirect - user must click button to go back
      
    } catch (error) {
      console.error('Submit error:', error)
      setSubmitting(false)
      setErrors({ submit: '送信に失敗しました。もう一度お試しください。' })
    }
  }

  const handleChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  if (submitted) {
    return (
      <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
        <ACTopBar leading={<ACBack />} title='お問い合わせ' />
        <div style={{ flex: 1, overflow: 'auto', padding: '20px 20px 40px' }} className='ac-scroll'>
          <div style={{ maxWidth: 600, margin: '0 auto', textAlign: 'center', paddingTop: 60 }}>
            <div
              style={{
                width: 80,
                height: 80,
                borderRadius: '50%',
                background: A.success,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                margin: '0 auto 24px',
              }}>
              <svg width='40' height='40' viewBox='0 0 24 24' fill='none' stroke={A.white} strokeWidth='2.5' strokeLinecap='round' strokeLinejoin='round'>
                <path d='M5 13l4 4L19 7' />
              </svg>
            </div>
            <h2 className='ac-serif' style={{ fontSize: 24, fontWeight: 600, color: A.ink900, margin: '0 0 12px' }}>
              送信完了
            </h2>
            <p style={{ fontSize: 14, color: A.ink700, lineHeight: 1.8, margin: '0 0 32px' }}>
              お問い合わせありがとうございます。<br />
              2営業日以内にご返信いたします。
            </p>
            <ACButton size='lg' onClick={() => nav.go('home', { replace: true })}>
              ホームに戻る
            </ACButton>
            <p style={{ fontSize: 12, color: A.ink500, marginTop: 16 }}>
              ボタンをクリックしてホームに戻ってください
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <ACTopBar
        leading={
          <button
            onClick={() => nav.back('mypage')}
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: 40,
              height: 40,
              background: 'transparent',
              border: 'none',
              cursor: 'pointer',
              padding: 0,
            }}>
            <svg width='24' height='24' viewBox='0 0 24 24' fill='none' stroke={A.ink900} strokeWidth='2' strokeLinecap='round' strokeLinejoin='round'>
              <path d='M15 18l-6-6 6-6' />
            </svg>
          </button>
        }
        title='お問い合わせ'
      />
      <div style={{ flex: 1, overflow: 'auto', padding: '20px 20px 40px' }} className='ac-scroll'>
        <div style={{ maxWidth: 600, margin: '0 auto' }}>
          <div style={{ marginBottom: 24 }}>
            <h1 className='ac-serif' style={{ fontSize: 24, fontWeight: 600, color: A.ink900, margin: '0 0 8px' }}>
              お問い合わせ
            </h1>
            <p style={{ fontSize: 13, color: A.ink500, margin: 0, lineHeight: 1.6 }}>
              ご質問やご不明な点がございましたら、以下のフォームよりお気軽にお問い合わせください。
            </p>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div>
              <label style={{ display: 'block', fontSize: 14, fontWeight: 600, color: A.ink900, marginBottom: 8 }}>
                お名前 <span style={{ color: A.danger }}>*</span>
              </label>
              <input
                type='text'
                value={formData.name}
                onChange={(e) => handleChange('name', e.target.value)}
                placeholder='山田 太郎'
                style={{
                  width: '100%',
                  padding: '14px 16px',
                  fontSize: 14,
                  border: `1px solid ${errors.name ? A.danger : A.ink100}`,
                  borderRadius: 10,
                  background: A.white,
                  color: A.ink900,
                  fontFamily: 'inherit',
                  outline: 'none',
                  boxSizing: 'border-box',
                }}
              />
              {errors.name && <p style={{ fontSize: 12, color: A.danger, marginTop: 6, margin: '6px 0 0' }}>{errors.name}</p>}
            </div>

            <div>
              <label style={{ display: 'block', fontSize: 14, fontWeight: 600, color: A.ink900, marginBottom: 8 }}>
                メールアドレス <span style={{ color: A.danger }}>*</span>
              </label>
              <input
                type='email'
                value={formData.email}
                onChange={(e) => handleChange('email', e.target.value)}
                placeholder='example@email.com'
                style={{
                  width: '100%',
                  padding: '14px 16px',
                  fontSize: 14,
                  border: `1px solid ${errors.email ? A.danger : A.ink100}`,
                  borderRadius: 10,
                  background: A.white,
                  color: A.ink900,
                  fontFamily: 'inherit',
                  outline: 'none',
                  boxSizing: 'border-box',
                }}
              />
              {errors.email && <p style={{ fontSize: 12, color: A.danger, marginTop: 6, margin: '6px 0 0' }}>{errors.email}</p>}
            </div>

            <div>
              <label style={{ display: 'block', fontSize: 14, fontWeight: 600, color: A.ink900, marginBottom: 8 }}>
                件名 <span style={{ color: A.danger }}>*</span>
              </label>
              <input
                type='text'
                value={formData.subject}
                onChange={(e) => handleChange('subject', e.target.value)}
                placeholder='お問い合わせの件名'
                style={{
                  width: '100%',
                  padding: '14px 16px',
                  fontSize: 14,
                  border: `1px solid ${errors.subject ? A.danger : A.ink100}`,
                  borderRadius: 10,
                  background: A.white,
                  color: A.ink900,
                  fontFamily: 'inherit',
                  outline: 'none',
                  boxSizing: 'border-box',
                }}
              />
              {errors.subject && <p style={{ fontSize: 12, color: A.danger, marginTop: 6, margin: '6px 0 0' }}>{errors.subject}</p>}
            </div>

            <div>
              <label style={{ display: 'block', fontSize: 14, fontWeight: 600, color: A.ink900, marginBottom: 8 }}>
                お問い合わせ内容 <span style={{ color: A.danger }}>*</span>
              </label>
              <textarea
                value={formData.message}
                onChange={(e) => handleChange('message', e.target.value)}
                placeholder='お問い合わせ内容を10文字以上でご記入ください'
                rows={8}
                style={{
                  width: '100%',
                  padding: '14px 16px',
                  fontSize: 14,
                  border: `1px solid ${errors.message ? A.danger : A.ink100}`,
                  borderRadius: 10,
                  background: A.white,
                  color: A.ink900,
                  fontFamily: 'inherit',
                  outline: 'none',
                  resize: 'vertical',
                  boxSizing: 'border-box',
                  lineHeight: 1.6,
                }}
              />
              {errors.message && <p style={{ fontSize: 12, color: A.danger, marginTop: 6, margin: '6px 0 0' }}>{errors.message}</p>}
              <p style={{ fontSize: 11, color: A.ink500, marginTop: 6, textAlign: 'right' }}>
                {formData.message.length} 文字
              </p>
            </div>

            <div
              style={{
                background: A.gold100,
                borderRadius: 10,
                padding: '14px 16px',
                fontSize: 12,
                color: A.ink700,
                lineHeight: 1.6,
              }}>
              <p style={{ margin: '0 0 8px', fontWeight: 600 }}>ご注意ください</p>
              <p style={{ margin: 0 }}>
                ・2営業日以内にご返信いたします<br />
                ・お急ぎの場合は、お電話でのお問い合わせもご利用ください
              </p>
            </div>

            <ACButton 
              size='lg' 
              onClick={handleSubmit} 
              disabled={submitted || submitting}
              loading={submitting}
            >
              {submitting ? '送信中...' : submitted ? '送信完了' : '送信する'}
            </ACButton>
            {errors.submit && (
              <div style={{
                marginTop: 12,
                padding: '12px 16px',
                background: '#FEE2E2',
                borderRadius: 10,
                border: '1px solid #FECACA',
                display: 'flex',
                alignItems: 'center',
                gap: 10,
              }}>
                <svg width='20' height='20' viewBox='0 0 24 24' fill='none' stroke={A.danger} strokeWidth='2' strokeLinecap='round' strokeLinejoin='round'>
                  <circle cx='12' cy='12' r='10' />
                  <path d='M12 8v4M12 16h.01' />
                </svg>
                <p style={{ fontSize: 13, color: A.danger, margin: 0, flex: 1 }}>{errors.submit}</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { A13Record, A14Tracker, A15Messages, A16Payments, A17Notifications, A18MyPage, A22TermsOfService, A23PrivacyPolicy, A24Help, A25Contact });
