// app.jsx — 최상위 컴포넌트 + Tweaks

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroCopyId": "sharp",
  "fontId": "pretendard"
}/*EDITMODE-END*/;

const FONT_PRESETS = [
  {
    id: 'pretendard',
    label: '01 · MODERN SANS',
    title: 'Pretendard · 모던 산세리프',
    sample: '혼자 실패하지 마세요',
    body: "'Pretendard Variable', Pretendard, -apple-system, sans-serif",
    display: "'Pretendard Variable', Pretendard, -apple-system, sans-serif",
    displayWeight: 600,
    displayTracking: '-0.035em',
  },
  {
    id: 'mixed-myeongjo',
    label: '02 · SANS + 명조',
    title: '본문 Pretendard · 헤드라인 명조',
    sample: '혼자 실패하지 마세요',
    body: "'Pretendard Variable', Pretendard, -apple-system, sans-serif",
    display: "'Nanum Myeongjo', 'Gowun Batang', serif",
    displayWeight: 600,
    displayTracking: '-0.025em',
  },
  {
    id: 'wanted',
    label: '03 · SAAS SHARP',
    title: 'Wanted Sans · 샤프한 SaaS',
    sample: '혼자 실패하지 마세요',
    body: "'Wanted Sans Variable', 'Wanted Sans', -apple-system, sans-serif",
    display: "'Wanted Sans Variable', 'Wanted Sans', sans-serif",
    displayWeight: 600,
    displayTracking: '-0.04em',
  },
  {
    id: 'plex',
    label: '04 · HUMANIST',
    title: 'IBM Plex Sans KR · 차분한 휴먼',
    sample: '혼자 실패하지 마세요',
    body: "'IBM Plex Sans KR', 'Pretendard Variable', sans-serif",
    display: "'IBM Plex Sans KR', 'Pretendard Variable', sans-serif",
    displayWeight: 600,
    displayTracking: '-0.025em',
  },
];

const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function getLaunchAlertContent(platform) {
  if (platform === 'ios') {
    return {
      eyebrow: 'iOS 출시 알림',
      title: 'iPhone 버전이 열리면 가장 먼저 알려드릴게요.',
      description: '이메일만 남겨주시면 iOS 출시 소식과 얼리 액세스 안내를 순서대로 보내드려요.',
    };
  }

  if (platform === 'android') {
    return {
      eyebrow: 'Android 출시 알림',
      title: 'Android 버전이 열리면 가장 먼저 알려드릴게요.',
      description: '이메일만 남겨주시면 Android 출시 소식과 얼리 액세스 안내를 순서대로 보내드려요.',
    };
  }

  return {
    eyebrow: '출시 알림 받기',
    title: '키토메이트가 출시되면 가장 먼저 알려드릴게요.',
    description: '지금은 사전 등록을 받고 있어요. 메일 주소를 남겨주시면 출시 소식과 베타 오픈 안내를 보내드려요.',
  };
}

function getCookie(name) {
  if (typeof document === 'undefined') return '';
  const match = document.cookie.match(new RegExp('(^|; )' + name + '=([^;]+)'));
  return match ? decodeURIComponent(match[2]) : '';
}

function getFbc() {
  const existing = getCookie('_fbc');
  if (existing) return existing;
  if (typeof window === 'undefined') return '';
  const fbclid = new URLSearchParams(window.location.search).get('fbclid');
  if (!fbclid) return '';
  return `fb.1.${Date.now()}.${fbclid}`;
}

function LaunchAlertModal({ open, context, onClose }) {
  const [email, setEmail] = React.useState('');
  const [status, setStatus] = React.useState('idle');
  const [message, setMessage] = React.useState('');
  const inputRef = React.useRef(null);
  const content = getLaunchAlertContent(context.platform);

  React.useEffect(() => {
    if (!open) return undefined;

    setEmail('');
    setStatus('idle');
    setMessage('');

    const timer = window.setTimeout(() => {
      if (inputRef.current) inputRef.current.focus();
    }, 40);

    return () => window.clearTimeout(timer);
  }, [open, context.platform, context.source]);

  React.useEffect(() => {
    if (!open) return undefined;

    const previousOverflow = document.body.style.overflow;
    const onKeyDown = (event) => {
      if (event.key === 'Escape') onClose();
    };

    document.body.style.overflow = 'hidden';
    window.addEventListener('keydown', onKeyDown);

    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener('keydown', onKeyDown);
    };
  }, [open, onClose]);

  if (!open) return null;

  const handleSubmit = async (event) => {
    event.preventDefault();

    const normalizedEmail = email.trim().toLowerCase();
    if (!EMAIL_PATTERN.test(normalizedEmail)) {
      setStatus('error');
      setMessage('올바른 이메일 주소를 입력해주세요.');
      return;
    }

    setStatus('submitting');
    setMessage('');

    try {
      const response = await fetch('/api/launch-alert', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: normalizedEmail,
          platform: context.platform || 'all',
          source: context.source || 'unknown',
          page: window.location.pathname,
          url: window.location.href,
          fbp: getCookie('_fbp'),
          fbc: getFbc(),
        }),
      });

      const result = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(result.message || '등록 중 문제가 발생했습니다. 잠시 후 다시 시도해주세요.');
      }

      setStatus('success');
      setMessage(result.message || '출시 알림 등록이 완료됐어요. 오픈 소식을 메일로 보내드릴게요.');

      if (typeof window !== 'undefined' && typeof window.fbq === 'function') {
        const eventOptions = result.event_id ? { eventID: result.event_id } : undefined;
        window.fbq('track', 'Lead', {
          content_name: 'launch_alert',
          content_category: context.platform || 'all',
          source: context.source || 'unknown',
        }, eventOptions);
      }

      if (typeof window !== 'undefined' && window.amplitude && typeof window.amplitude.track === 'function') {
        window.amplitude.track('Launch Alert Submitted', {
          platform: context.platform || 'all',
          source: context.source || 'unknown',
          page: window.location.pathname,
        });
      }
    } catch (error) {
      setStatus('error');
      setMessage(error.message || '등록 중 문제가 발생했습니다. 잠시 후 다시 시도해주세요.');
    }
  };

  return (
    <div className="modal-backdrop" role="presentation" onClick={onClose}>
      <div className="waitlist-modal" role="dialog" aria-modal="true" aria-labelledby="launch-alert-title" onClick={(event) => event.stopPropagation()}>
        <button type="button" className="waitlist-close" aria-label="출시 알림 모달 닫기" onClick={onClose}>
          ×
        </button>

        <div className="waitlist-eyebrow">
          <Icon name="bell-ring" size={14} strokeWidth={2.2} />
          {content.eyebrow}
        </div>
        <h2 id="launch-alert-title" className="waitlist-title serif">{content.title}</h2>
        <p className="waitlist-description">{content.description}</p>
        <div className="waitlist-offer">
          <Icon name="gift" size={18} strokeWidth={2.3} />
          <strong>사전등록을 완료하면 출시 후 7일 무료로 사용할 수 있어요.</strong>
        </div>

        <div className="waitlist-meta">
          <span className="waitlist-chip">사전 등록</span>
          <span className="waitlist-chip">메일 한 번만 입력</span>
          <span className="waitlist-chip">언제든 수신 해지 가능</span>
        </div>

        {status === 'success' ? (
          <div className="waitlist-success">
            <div className="waitlist-success-icon">
              <Icon name="check" size={22} strokeWidth={2.5} />
            </div>
            <div className="waitlist-success-title serif">등록 완료</div>
            <div className="waitlist-success-body">{message}</div>
            <button type="button" className="btn btn-primary btn-lg" style={{ width: '100%', marginTop: 18 }} onClick={onClose}>
              확인
            </button>
          </div>
        ) : (
          <form className="waitlist-form" onSubmit={handleSubmit}>
            <label className="waitlist-label" htmlFor="launch-alert-email">이메일 주소</label>
            <input
              ref={inputRef}
              id="launch-alert-email"
              className="waitlist-input"
              type="email"
              inputMode="email"
              autoComplete="email"
              placeholder="you@example.com"
              value={email}
              onChange={(event) => setEmail(event.target.value)}
              disabled={status === 'submitting'}
            />

            <button type="submit" className="btn btn-primary btn-lg" style={{ width: '100%' }} disabled={status === 'submitting'}>
              {status === 'submitting' ? '등록 중...' : '출시 알림 받기'}
            </button>

            <div className={'waitlist-feedback' + (status === 'error' ? ' is-error' : '')}>
              {message}
            </div>

            <p className="waitlist-note">
              제출 시 키토메이트의 출시 소식과 베타 안내 메일 수신에 동의한 것으로 간주됩니다.
              원치 않으시면 메일에서 언제든 수신 해지할 수 있어요.
            </p>
          </form>
        )}
      </div>
    </div>
  );
}

function App() {
  const [heroCopyId, setHeroCopyId] = React.useState(TWEAK_DEFAULTS.heroCopyId);
  const [fontId, setFontId] = React.useState(TWEAK_DEFAULTS.fontId || 'pretendard');
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const [launchAlert, setLaunchAlert] = React.useState({ open: false, platform: 'all', source: 'unknown' });

  React.useEffect(() => {
    const listener = (e) => {
      if (!e.data) return;
      if (e.data.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', listener);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', listener);
  }, []);

  // Apply font preset to :root
  React.useEffect(() => {
    const preset = FONT_PRESETS.find(p => p.id === fontId) || FONT_PRESETS[0];
    const r = document.documentElement.style;
    r.setProperty('--font-body', preset.body);
    r.setProperty('--font-display', preset.display);
    r.setProperty('--font-display-weight', preset.displayWeight);
    r.setProperty('--font-display-tracking', preset.displayTracking);
  }, [fontId]);

  const pickHero = (id) => {
    setHeroCopyId(id);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { heroCopyId: id } }, '*');
  };
  const pickFont = (id) => {
    setFontId(id);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { fontId: id } }, '*');
  };
  const openLaunchAlert = (nextContext = {}) => {
    setLaunchAlert({
      open: true,
      platform: nextContext.platform || 'all',
      source: nextContext.source || 'unknown',
    });
  };
  const closeLaunchAlert = () => {
    setLaunchAlert((current) => ({ ...current, open: false }));
  };

  return (
    <div>
      <SiteHeader onOpenLaunchAlert={openLaunchAlert}/>
      <Hero copyId={heroCopyId} onOpenLaunchAlert={openLaunchAlert}/>
      <ProblemSection/>
      <FeaturesSection/>
      <TestimonialsSection/>
      <PricingSection onOpenLaunchAlert={openLaunchAlert}/>
      <FAQSection/>
      <FinalCTA onOpenLaunchAlert={openLaunchAlert}/>
      <LaunchAlertModal open={launchAlert.open} context={launchAlert} onClose={closeLaunchAlert}/>

      {tweaksOpen && (
        <div className="tweaks-panel" role="dialog" aria-label="Tweaks">
          <h3>
            Tweaks
            <button type="button" onClick={() => setTweaksOpen(false)} aria-label="Tweaks 패널 닫기" style={{ color: 'var(--ink-mute)', fontSize: 16, width: 28, height: 28, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>×</button>
          </h3>

          <div style={{ fontSize: 10, color: 'var(--ink-mute)', textTransform: 'uppercase', letterSpacing: '0.1em', marginTop: 14, marginBottom: 8, fontWeight: 700 }}>폰트</div>
          {FONT_PRESETS.map(f => (
            <button key={f.id} type="button"
              className={'tweak-option ' + (f.id === fontId ? 'active' : '')}
              aria-pressed={f.id === fontId}
              onClick={() => pickFont(f.id)}
              style={{ padding: '12px 14px', width: '100%', textAlign: 'left', display: 'block', font: 'inherit' }}>
              <div className="tweak-label">{f.label}</div>
              <div className="tweak-title" style={{ marginTop: 4 }}>{f.title}</div>
              <div style={{
                fontFamily: f.display,
                fontWeight: f.displayWeight,
                letterSpacing: f.displayTracking,
                fontSize: 20,
                marginTop: 8,
                color: 'var(--ink)',
                lineHeight: 1.2,
              }}>{f.sample}</div>
            </button>
          ))}

          <div style={{ fontSize: 10, color: 'var(--ink-mute)', textTransform: 'uppercase', letterSpacing: '0.1em', marginTop: 18, marginBottom: 8, fontWeight: 700 }}>히어로 카피</div>
          {HERO_COPY.map(c => (
            <button key={c.id} type="button"
              className={'tweak-option ' + (c.id === heroCopyId ? 'active' : '')}
              aria-pressed={c.id === heroCopyId}
              onClick={() => pickHero(c.id)}
              style={{ width: '100%', textAlign: 'left', display: 'block', font: 'inherit' }}>
              <div className="tweak-label">{c.label}</div>
              <div className="tweak-title">{c.eyebrow}</div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
