
const Taegeuk = ({ size = 80, color1 = '#a8332a', color2 = '#1a3a6e', stroke = '#1a1a1a', opacity = 1 }) => (
  <svg width={size} height={size} viewBox="0 0 100 100" style={{ opacity }}>
    <defs>
      <clipPath id={`taeguk-clip-${size}`}>
        <circle cx="50" cy="50" r="48" />
      </clipPath>
    </defs>
    <g clipPath={`url(#taeguk-clip-${size})`}>
      <path d="M 50 2 A 48 48 0 0 1 50 98 A 24 24 0 0 1 50 50 A 24 24 0 0 0 50 2 Z" fill={color1} />
      <path d="M 50 2 A 48 48 0 0 0 50 98 A 24 24 0 0 0 50 50 A 24 24 0 0 1 50 2 Z" fill={color2} />
    </g>
    <circle cx="50" cy="50" r="48" fill="none" stroke={stroke} strokeWidth="1" />
  </svg>
);

const TRIGRAMS = [
  [1, 1, 1], [1, 1, 0], [1, 0, 1], [1, 0, 0],
  [0, 1, 1], [0, 1, 0], [0, 0, 1], [0, 0, 0],
];

const Trigram = ({ bars, size = 30, color = '#1a1a1a' }) => {
  const w = size;
  const h = size * 0.6;
  const lineH = h / 7;
  const gap = lineH;
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`}>
      {bars.map((b, i) => {
        const y = i * (lineH + gap) + lineH * 0.5;
        if (b === 1) return <rect key={i} x="0" y={y} width={w} height={lineH} fill={color} />;
        const segW = (w - w * 0.18) / 2;
        return (
          <g key={i}>
            <rect x="0" y={y} width={segW} height={lineH} fill={color} />
            <rect x={w - segW} y={y} width={segW} height={lineH} fill={color} />
          </g>
        );
      })}
    </svg>
  );
};

const PalgwaeCircle = ({ size = 200, color = '#1a1a1a', opacity = 0.85 }) => {
  const radius = size * 0.42;
  const cx = size / 2;
  const cy = size / 2;
  const trigramSize = size * 0.18;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ opacity }}>
      <circle cx={cx} cy={cy} r={radius * 0.95} fill="none" stroke={color} strokeWidth="0.8" opacity="0.5" />
      <g transform={`translate(${cx - size * 0.175}, ${cy - size * 0.175})`}>
        <Taegeuk size={size * 0.35} color1="#a8332a" color2="#1a1a1a" stroke={color} />
      </g>
      {TRIGRAMS.map((bars, i) => {
        const angle = (i / 8) * Math.PI * 2 - Math.PI / 2;
        const x = cx + Math.cos(angle) * radius - trigramSize / 2;
        const y = cy + Math.sin(angle) * radius - trigramSize * 0.3;
        return (
          <g key={i} transform={`translate(${x}, ${y})`}>
            <Trigram bars={bars} size={trigramSize} color={color} />
          </g>
        );
      })}
    </svg>
  );
};

const CloudMotif = ({ size = 120, color = '#1a1a1a', opacity = 0.6 }) => (
  <svg width={size} height={size * 0.5} viewBox="0 0 200 100" style={{ opacity }}>
    <path
      d="M 20 60 Q 20 40, 40 40 Q 45 25, 65 30 Q 75 18, 95 25 Q 110 15, 125 30 Q 145 25, 150 45 Q 170 45, 170 65 Q 170 80, 150 80 L 40 80 Q 20 80, 20 60 Z"
      fill="none" stroke={color} strokeWidth="1.2"
    />
    <path d="M 50 55 Q 60 50, 65 55 Q 70 50, 75 55" fill="none" stroke={color} strokeWidth="0.8" />
    <path d="M 105 55 Q 115 50, 120 55 Q 125 50, 130 55" fill="none" stroke={color} strokeWidth="0.8" />
  </svg>
);

const FlowerMotif = ({ size = 60, color = '#a8332a', opacity = 0.85 }) => {
  const cx = 50, cy = 50, petals = 6;
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={{ opacity }}>
      {Array.from({ length: petals }).map((_, i) => (
        <ellipse key={i} cx={cx} cy={cy - 22} rx="9" ry="18" fill={color}
          transform={`rotate(${(i / petals) * 360} ${cx} ${cy})`} opacity="0.9" />
      ))}
      <circle cx={cx} cy={cy} r="8" fill="#f4ecd8" stroke={color} strokeWidth="1.5" />
      <circle cx={cx} cy={cy} r="3" fill={color} />
    </svg>
  );
};

const ZODIAC_HANJA = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];

const ZodiacRing = ({ size = 240, color = '#1a1a1a', accent = '#a8332a', opacity = 0.9 }) => {
  const cx = size / 2, cy = size / 2;
  const rOuter = size * 0.46, rInner = size * 0.36;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ opacity }}>
      <circle cx={cx} cy={cy} r={rOuter} fill="none" stroke={color} strokeWidth="0.6" opacity="0.4" />
      <circle cx={cx} cy={cy} r={rInner} fill="none" stroke={color} strokeWidth="0.6" opacity="0.4" />
      {ZODIAC_HANJA.map((h, i) => {
        const angle = (i / 12) * Math.PI * 2 - Math.PI / 2;
        const r = (rOuter + rInner) / 2;
        return (
          <text key={i}
            x={cx + Math.cos(angle) * r} y={cy + Math.sin(angle) * r}
            textAnchor="middle" dominantBaseline="central"
            fontSize={size * 0.06} fill={i % 3 === 0 ? accent : color}
            style={{ fontFamily: 'Noto Serif KR, serif', fontWeight: 500 }}
          >{h}</text>
        );
      })}
      {Array.from({ length: 12 }).map((_, i) => {
        const angle = (i / 12) * Math.PI * 2 - Math.PI / 2;
        return (
          <line key={i}
            x1={cx + Math.cos(angle) * rInner} y1={cy + Math.sin(angle) * rInner}
            x2={cx + Math.cos(angle) * rOuter} y2={cy + Math.sin(angle) * rOuter}
            stroke={color} strokeWidth="0.4" opacity="0.3"
          />
        );
      })}
    </svg>
  );
};

const Seal = ({ text = '白楊', size = 64, color = '#a8332a' }) => (
  <svg width={size} height={size} viewBox="0 0 100 100">
    <rect x="4" y="4" width="92" height="92" fill={color} rx="2" />
    <rect x="8" y="8" width="84" height="84" fill="none" stroke="#f4ecd8" strokeWidth="1.5" />
    <text x="50" y="34" textAnchor="middle" dominantBaseline="central"
      fontSize="34" fill="#f4ecd8"
      style={{ fontFamily: 'Noto Serif KR, serif', fontWeight: 700, letterSpacing: '0.05em' }}>
      {text[0]}
    </text>
    <text x="50" y="72" textAnchor="middle" dominantBaseline="central"
      fontSize="34" fill="#f4ecd8"
      style={{ fontFamily: 'Noto Serif KR, serif', fontWeight: 700 }}>
      {text[1] || ''}
    </text>
  </svg>
);

const Divider = ({ width = 200, color = '#1a1a1a', opacity = 0.4 }) => (
  <svg width={width} height="14" viewBox={`0 0 ${width} 14`} style={{ opacity }}>
    <line x1="0" y1="7" x2={width / 2 - 8} y2="7" stroke={color} strokeWidth="0.6" />
    <line x1={width / 2 + 8} y1="7" x2={width} y2="7" stroke={color} strokeWidth="0.6" />
    <path d={`M ${width / 2} 3 L ${width / 2 + 4} 7 L ${width / 2} 11 L ${width / 2 - 4} 7 Z`} fill={color} />
  </svg>
);

const HANJI_TEXTURE_DATA_URL = `data:image/svg+xml;utf8,${encodeURIComponent(`
<svg xmlns='http://www.w3.org/2000/svg' width='240' height='240'>
  <filter id='n'>
    <feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' seed='3'/>
    <feColorMatrix values='0 0 0 0 0.55 0 0 0 0 0.45 0 0 0 0 0.30 0 0 0 0.10 0'/>
  </filter>
  <rect width='240' height='240' filter='url(#n)' opacity='0.6'/>
  <filter id='f'>
    <feTurbulence type='turbulence' baseFrequency='0.012' numOctaves='2' seed='5'/>
    <feColorMatrix values='0 0 0 0 0.45 0 0 0 0 0.35 0 0 0 0 0.20 0 0 0 0.06 0'/>
  </filter>
  <rect width='240' height='240' filter='url(#f)'/>
</svg>
`)}`;

window.__patterns = { Taegeuk, PalgwaeCircle, CloudMotif, FlowerMotif, ZodiacRing, Seal, Divider, HANJI_TEXTURE_DATA_URL };



const { useState: useStateFlow, useEffect: useEffectFlow, useCallback: useCallbackFlow } = React;

// ══════════════════════════════════════════════════════════
//  설정값 — 실제 서비스 전 아래 값을 교체해 주세요
// ══════════════════════════════════════════════════════════
const CONFIG = {
  // ── EmailJS (https://www.emailjs.com) ──────────────────
  // 1) EmailJS 가입 후 Service, Template 2개 생성
  // 2) Public Key는 Account > API Keys에서 확인
  EMAILJS_PUBLIC_KEY:        'YOUR_EMAILJS_PUBLIC_KEY',   // 예: 'abc123xyz'
  EMAILJS_SERVICE_ID:        'YOUR_SERVICE_ID',            // 예: 'service_xxxx'
  EMAILJS_ADMIN_TEMPLATE:    'template_order_admin',       // 관리자 알림 템플릿 ID
  EMAILJS_CUSTOMER_TEMPLATE: 'template_order_customer',    // 고객 확인 템플릿 ID
  EMAILJS_INQUIRY_TEMPLATE:  'template_inquiry',           // 문의 템플릿 ID

  // ── 관리자 이메일 ───────────────────────────────────────
  ADMIN_EMAIL: 'by4lucky@gmail.com',

  // ── 토스페이먼츠 v2 (https://developers.tosspayments.com) ─
  // 토스페이먼츠 대시보드 > 개발 연동 > API 키에서 확인
  // 테스트: test_ck_... / 라이브: live_ck_...
  // 아래 값을 실제 클라이언트 키로 교체해 주세요
  TOSS_CLIENT_KEY: 'test_ck_YOUR_CLIENT_KEY',
};

// EmailJS 초기화 + CONFIG 전역 노출 (리다이렉트 후 복원용)
window.__CONFIG__ = CONFIG;
(function initEmailJS() {
  if (window.emailjs && CONFIG.EMAILJS_PUBLIC_KEY !== 'YOUR_EMAILJS_PUBLIC_KEY') {
    try { emailjs.init({ publicKey: CONFIG.EMAILJS_PUBLIC_KEY }); } catch (_) {}
  }
})();

const { Taegeuk: _Taegeuk, ZodiacRing: _ZodiacRing, Seal: _Seal, Divider: _Divider,
        CloudMotif: _CloudMotif, HANJI_TEXTURE_DATA_URL: _HANJI } = window.__patterns;

// ─── 폼 기본 컴포넌트 ──────────────────────────────────────

const FSelect = ({ value, onChange, options, placeholder, palette }) => (
  <select value={value} onChange={(e) => onChange(e.target.value)} style={{
    width: '100%', padding: '12px 14px', fontSize: 16,
    fontFamily: 'Nanum Myeongjo, serif',
    background: palette.paper, border: `1px solid ${palette.line}`, borderRadius: 0,
    color: value ? palette.ink : palette.muted, cursor: 'pointer', outline: 'none',
    appearance: 'none', minHeight: 48,
    backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'><path d='M1 1 L6 6 L11 1' stroke='${encodeURIComponent(palette.ink)}' stroke-width='1' fill='none'/></svg>")`,
    backgroundRepeat: 'no-repeat', backgroundPosition: 'right 14px center',
  }}>
    {placeholder && <option value="">{placeholder}</option>}
    {options.map((o) => (
      <option key={o.value ?? o} value={o.value ?? o}>{o.label ?? o}</option>
    ))}
  </select>
);

const FInput = ({ value, onChange, placeholder, palette, type = 'text' }) => (
  <input type={type} value={value} onChange={(e) => onChange(e.target.value)}
    placeholder={placeholder} style={{
      width: '100%', padding: '12px 14px', fontSize: 16,
      fontFamily: 'Nanum Myeongjo, serif',
      background: palette.paper, border: `1px solid ${palette.line}`, borderRadius: 0,
      color: palette.ink, outline: 'none', boxSizing: 'border-box', minHeight: 48,
    }}
  />
);

const FLabel = ({ children, palette, required }) => (
  <label style={{
    display: 'block', fontSize: 13, fontFamily: 'Nanum Myeongjo, serif',
    color: palette.ink, marginBottom: 8, letterSpacing: '0.02em',
  }}>
    {children}{required && <span style={{ color: palette.accent, marginLeft: 4 }}>*</span>}
  </label>
);

// ─── 생년월일 입력 블록 ────────────────────────────────────

const BirthBlock = ({ data, onChange, palette, label = '본인' }) => {
  const years = Array.from({ length: 90 }, (_, i) => 2010 - i);
  const months = Array.from({ length: 12 }, (_, i) => i + 1);
  const days = Array.from({ length: 31 }, (_, i) => i + 1);
  const isMobileDevice = useStateFlow(() =>
    typeof window !== 'undefined' && window.matchMedia('(max-width: 640px), (pointer: coarse)').matches
  )[0];
  const [useNativeDate, setUseNativeDate] = useStateFlow(isMobileDevice);
  const isoDate = (data.year && data.month && data.day)
    ? `${data.year}-${String(data.month).padStart(2, '0')}-${String(data.day).padStart(2, '0')}` : '';
  const handleNativeDate = (val) => {
    if (!val) { onChange({ ...data, year: '', month: '', day: '' }); return; }
    const [y, m, d] = val.split('-').map((s) => parseInt(s, 10));
    onChange({ ...data, year: y, month: m, day: d });
  };
  const hours = [
    { value: '', label: '시간 모름' },
    { value: '子', label: '자시 (23:30 ~ 01:30)' }, { value: '丑', label: '축시 (01:30 ~ 03:30)' },
    { value: '寅', label: '인시 (03:30 ~ 05:30)' }, { value: '卯', label: '묘시 (05:30 ~ 07:30)' },
    { value: '辰', label: '진시 (07:30 ~ 09:30)' }, { value: '巳', label: '사시 (09:30 ~ 11:30)' },
    { value: '午', label: '오시 (11:30 ~ 13:30)' }, { value: '未', label: '미시 (13:30 ~ 15:30)' },
    { value: '申', label: '신시 (15:30 ~ 17:30)' }, { value: '酉', label: '유시 (17:30 ~ 19:30)' },
    { value: '戌', label: '술시 (19:30 ~ 21:30)' }, { value: '亥', label: '해시 (21:30 ~ 23:30)' },
  ];
  return (
    <div style={{ marginBottom: 28 }}>
      <FLabel palette={palette} required>{label} 정보</FLabel>
      <div style={{ display: 'grid', gap: 10 }}>
        <FInput value={data.name} onChange={(v) => onChange({ ...data, name: v })} placeholder="성함" palette={palette} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <FSelect value={data.gender} onChange={(v) => onChange({ ...data, gender: v })}
            options={[{ value: 'M', label: '남(乾)' }, { value: 'F', label: '여(坤)' }]}
            placeholder="성별" palette={palette} />
          <FSelect value={data.calendar} onChange={(v) => onChange({ ...data, calendar: v })}
            options={[{ value: 'solar', label: '양력' }, { value: 'lunar', label: '음력' }, { value: 'lunar_leap', label: '음력 (윤달)' }]}
            placeholder="달력" palette={palette} />
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 4, marginBottom: -4 }}>
          <span style={{ fontSize: 12, color: palette.muted, letterSpacing: '0.02em' }}>태어난 날</span>
          <button type="button" onClick={() => setUseNativeDate((v) => !v)} style={{
            background: 'transparent', border: 'none', padding: '2px 0', fontSize: 11,
            color: palette.accent, fontFamily: 'Nanum Myeongjo, serif', cursor: 'pointer',
            letterSpacing: '0.05em', textDecoration: 'underline', textUnderlineOffset: 3,
          }}>
            {useNativeDate ? '연·월·일 따로 고르기' : '달력에서 고르기'}
          </button>
        </div>
        {useNativeDate ? (
          <input type="date" value={isoDate} onChange={(e) => handleNativeDate(e.target.value)}
            min="1925-01-01" max={new Date().toISOString().slice(0, 10)} style={{
              width: '100%', padding: '12px 14px', fontSize: 16, fontFamily: 'Nanum Myeongjo, serif',
              background: palette.paper, border: `1px solid ${palette.line}`, borderRadius: 0,
              color: isoDate ? palette.ink : palette.muted, outline: 'none', boxSizing: 'border-box', minHeight: 48,
            }} />
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr 1fr', gap: 10 }}>
            <FSelect value={data.year} onChange={(v) => onChange({ ...data, year: v })}
              options={years.map((y) => ({ value: y, label: `${y}년` }))} placeholder="태어난 해" palette={palette} />
            <FSelect value={data.month} onChange={(v) => onChange({ ...data, month: v })}
              options={months.map((m) => ({ value: m, label: `${m}월` }))} placeholder="월" palette={palette} />
            <FSelect value={data.day} onChange={(v) => onChange({ ...data, day: v })}
              options={days.map((d) => ({ value: d, label: `${d}일` }))} placeholder="일" palette={palette} />
          </div>
        )}
        <FSelect value={data.hour} onChange={(v) => onChange({ ...data, hour: v })}
          options={hours} placeholder="태어난 시" palette={palette} />
      </div>
    </div>
  );
};

const emptyPerson = { name: '', gender: '', calendar: 'solar', year: '', month: '', day: '', hour: '' };

// ─── 서비스 플로우 모달 ────────────────────────────────────

const ServiceFlow = ({ service, onClose, palette }) => {
  const isGunghap = service === 'gunghap';
  const [step, setStep] = useStateFlow(1);
  const [person1, setPerson1] = useStateFlow({ ...emptyPerson });
  const [person2, setPerson2] = useStateFlow({ ...emptyPerson });
  const [email, setEmail] = useStateFlow('');
  const [phone, setPhone] = useStateFlow('');
  const [question, setQuestion] = useStateFlow('');
  const [agree, setAgree] = useStateFlow(false);
  const [paymentMethod, setPaymentMethod] = useStateFlow('card');
  const [processing, setProcessing] = useStateFlow(false);
  const [orderNumber, setOrderNumber] = useStateFlow('');
  const [payError, setPayError] = useStateFlow('');

  const price = isGunghap ? 40000 : 25000;
  const original = isGunghap ? 50000 : 30000;
  const title = isGunghap ? '궁합풀이' : '사주풀이';
  const subtitle = isGunghap ? '두 분의 인연을 살펴드립니다' : '한 사람의 사주를 풀어드립니다';

  const validateStep1 = () => {
    const ok1 = person1.name && person1.gender && person1.year && person1.month && person1.day;
    const ok2 = !isGunghap || (person2.name && person2.gender && person2.year && person2.month && person2.day);
    return ok1 && ok2 && email && agree;
  };

  const fmt = (n) => n.toLocaleString('ko-KR');

  const genOrderNum = () => {
    const yy = new Date().getFullYear();
    const nn = String(Math.floor(Math.random() * 90000 + 10000));
    return `BY-${yy}-${nn}`;
  };

  // ── 주문 저장 + 이메일 알림 ─────────────────────────────
  const sendOrderNotification = async (orderNum, payStatus) => {
    const calLabel = (c) => c === 'solar' ? '양력' : c === 'lunar_leap' ? '음력(윤달)' : '음력';
    const birthStr = (p) => `${p.year}년 ${p.month}월 ${p.day}일 ${p.hour ? p.hour + '시' : '시각 미기재'} (${calLabel(p.calendar)})`;
    const genderLabel = (g) => g === 'M' ? '남(乾)' : g === 'F' ? '여(坤)' : '-';
    const payLabel = { card: '신용·체크카드', kakao: '카카오페이', naver: '네이버페이', bank: '계좌이체' };
    const statusLabel = payStatus === 'paid' ? '결제 완료' : '입금 대기';

    const params = {
      order_num:       orderNum,
      service:         title,
      price:           fmt(price) + '원',
      pay_method:      payLabel[paymentMethod] || paymentMethod,
      pay_status:      statusLabel,
      name1:           person1.name,
      gender1:         genderLabel(person1.gender),
      birth1:          birthStr(person1),
      name2:           isGunghap ? person2.name : '-',
      gender2:         isGunghap ? genderLabel(person2.gender) : '-',
      birth2:          isGunghap ? birthStr(person2) : '-',
      customer_email:  email,
      customer_phone:  phone || '-',
      question:        question || '없음',
      admin_email:     CONFIG.ADMIN_EMAIL,
    };

    // localStorage 저장 — 관리자 페이지와 연동 (v2 구조화 데이터)
    try {
      const v2Key = 'baekyangdang_orders_v2';
      const ordersV2 = JSON.parse(localStorage.getItem(v2Key) || '[]');
      
      const toDate = (p) => {
        if (!p.year || !p.month || !p.day) return new Date();
        return new Date(p.year, p.month - 1, p.day);
      };
      const genderMap = { M: '남', F: '여' };
      const calMap = { solar: '양력', lunar: '음력', lunar_leap: '음력(윤달)' };

      const newOrder = {
        id: orderNum,
        kind: isGunghap ? 'gunghap' : 'saju',
        status: payStatus === 'paid' ? 'paid' : 'hold',
        name: person1.name,
        gender: genderMap[person1.gender] || '남',
        birthDate: toDate(person1),
        birthSiji: person1.hour ? person1.hour + '시' : '시각 미기재',
        calendar: calMap[person1.calendar] || '양력',
        partner: isGunghap ? {
          name: person2.name,
          gender: genderMap[person2.gender] || '여',
          birthDate: toDate(person2),
          birthSiji: person2.hour ? person2.hour + '시' : '시각 미기재',
          calendar: calMap[person2.calendar] || '양력',
        } : null,
        email: email,
        phone: phone,
        note: question,
        submittedAt: new Date().toISOString(),
        paidAt: payStatus === 'paid' ? new Date().toISOString() : null,
        paid: payStatus === 'paid',
        channel: payLabel[paymentMethod] || paymentMethod,
        price: price,
        logs: [
          { at: new Date().toISOString(), what: '신청 접수' },
          { at: new Date().toISOString(), what: payStatus === 'paid' ? `결제 완료 · ${payLabel[paymentMethod]}` : '입금 대기' }
        ],
        adminNote: ''
      };

      ordersV2.unshift(newOrder);
      localStorage.setItem(v2Key, JSON.stringify(ordersV2.slice(0, 200)));

      // 기존 v1 데이터도 유지 (호환성)
      const key = 'baekyangdang_orders';
      const orders = JSON.parse(localStorage.getItem(key) || '[]');
      orders.unshift({ ...params, createdAt: new Date().toISOString(), status: payStatus });
      localStorage.setItem(key, JSON.stringify(orders.slice(0, 200)));
    } catch (_) {}

    // EmailJS 발송 (설정된 경우에만)
    if (!window.emailjs || CONFIG.EMAILJS_PUBLIC_KEY === 'YOUR_EMAILJS_PUBLIC_KEY') return;
    try {
      await Promise.all([
        emailjs.send(CONFIG.EMAILJS_SERVICE_ID, CONFIG.EMAILJS_ADMIN_TEMPLATE, params),
        emailjs.send(CONFIG.EMAILJS_SERVICE_ID, CONFIG.EMAILJS_CUSTOMER_TEMPLATE,
          { ...params, to_email: email, to_name: person1.name }),
      ]);
    } catch (e) {
      console.warn('[백양당] EmailJS 발송 실패:', e);
    }
  };

  // ── 고객 키 생성 (토스페이먼츠 v2 필수) ─────────────────
  const getCustomerKey = () => {
    const k = 'by_ck';
    let v = localStorage.getItem(k);
    if (!v) { v = 'BY_' + Date.now() + '_' + Math.random().toString(36).slice(2, 9); localStorage.setItem(k, v); }
    return v;
  };

  // ── 결제 처리 (토스페이먼츠 v2) ─────────────────────────
  const handlePayment = async () => {
    setProcessing(true);
    setPayError('');
    const orderNum = genOrderNum();

    // 리다이렉트 복원을 위해 주문 데이터 임시 저장
    const pendingOrder = {
      orderNum, service: title, price, email, phone,
      person1: { ...person1 }, person2: { ...person2 },
      isGunghap, question,
    };
    try { sessionStorage.setItem('by_pending_order', JSON.stringify(pendingOrder)); } catch (_) {}

    // ── 테스트 모드 (클라이언트 키 미설정 시) ───────────────
    if (!window.TossPayments || CONFIG.TOSS_CLIENT_KEY === 'test_ck_YOUR_CLIENT_KEY') {
      await new Promise((r) => setTimeout(r, 1400));
      await sendOrderNotification(orderNum, 'paid');
      setOrderNumber(orderNum);
      setStep(3);
      setProcessing(false);
      return;
    }

    // ── 토스페이먼츠 v2 실결제 ──────────────────────────────
    try {
      const tossPayments = TossPayments(CONFIG.TOSS_CLIENT_KEY);
      const payment = tossPayments.payment({ customerKey: getCustomerKey() });

      const base = location.origin + location.pathname;
      await payment.requestPayment({
        method: 'CARD',
        amount: { currency: 'KRW', value: price },
        orderId:   orderNum,
        orderName: `백양당 ${title}`,
        successUrl: `${base}?payment=success&orderId=${orderNum}`,
        failUrl:    `${base}?payment=fail&orderId=${orderNum}`,
        customerEmail:       email,
        customerName:        person1.name,
        customerMobilePhone: phone || undefined,
      });
      // requestPayment는 redirect이므로 이 아래 코드는 실패 시에만 도달
    } catch (e) {
      if (e && e.code !== 'USER_CANCEL') {
        setPayError(e.message || '결제 중 오류가 발생했습니다. 다시 시도해 주십시오.');
      }
      setProcessing(false);
    }
  };

  useEffectFlow(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div
      role="dialog" aria-modal="true"
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(26, 26, 26, 0.55)',
        display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
        padding: '40px 20px', overflowY: 'auto',
      }}
    >
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 560,
        background: palette.paper, backgroundImage: `url("${_HANJI}")`,
        border: `1px solid ${palette.line}`, padding: '40px 44px 44px',
        position: 'relative', fontFamily: 'Nanum Myeongjo, serif', color: palette.ink,
        boxShadow: '0 30px 80px rgba(0,0,0,0.25)',
      }}>
        <button onClick={onClose} aria-label="닫기" style={{
          position: 'absolute', top: 16, right: 16,
          background: 'transparent', border: 'none', fontSize: 22, cursor: 'pointer',
          color: palette.ink, opacity: 0.5, width: 32, height: 32, fontFamily: 'serif',
        }}>×</button>

        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 12 }}>
            {service === 'saju'
              ? <_ZodiacRing size={70} color={palette.ink} accent={palette.accent} opacity={0.85} />
              : <_Taegeuk size={50} color1={palette.accent} color2={palette.ink} stroke={palette.ink} />
            }
          </div>
          <h2 style={{ fontFamily: '"Gaegu", "Nanum Brush Script", serif', fontSize: 36, fontWeight: 400, margin: '0 0 6px', letterSpacing: '0.05em' }}>{title}</h2>
          <div style={{ fontSize: 13, color: palette.muted, letterSpacing: '0.05em' }}>{subtitle}</div>

          {/* 스테퍼 */}
          <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 0, marginTop: 22, fontSize: 12, color: palette.muted, letterSpacing: '0.06em' }}>
            {['정보 입력', '결제', '완료'].map((lbl, i) => {
              const sn = i + 1, active = step === sn, done = step > sn;
              return (
                <React.Fragment key={i}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 7, color: active ? palette.accent : done ? palette.ink : palette.muted, fontWeight: active ? 700 : 400 }}>
                    <span style={{ width: 20, height: 20, borderRadius: '50%', border: `1px solid ${active || done ? palette.accent : palette.line}`, background: active || done ? palette.accent : 'transparent', color: active || done ? palette.paper : palette.muted, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 600 }}>
                      {done ? '✓' : sn}
                    </span>
                    <span>{lbl}</span>
                  </div>
                  {i < 2 && <span style={{ width: 30, height: 1, background: palette.line, margin: '0 10px' }} />}
                </React.Fragment>
              );
            })}
          </div>
        </div>

        {/* Step 1: 정보 입력 */}
        {step === 1 && (
          <div>
            <BirthBlock data={person1} onChange={setPerson1} palette={palette} label={isGunghap ? '첫 번째 분' : '본인'} />
            {isGunghap && <BirthBlock data={person2} onChange={setPerson2} palette={palette} label="두 번째 분" />}
            <div style={{ marginBottom: 20 }}>
              <FLabel palette={palette} required>결과지를 받으실 이메일</FLabel>
              <FInput value={email} onChange={setEmail} placeholder="example@email.com" palette={palette} type="email" />
              <div style={{ fontSize: 12, color: palette.muted, marginTop: 6, lineHeight: 1.6 }}>
                선생께서 직접 풀이하신 결과지를 PDF로 보내드립니다. (영업일 기준 2~3일 소요)
              </div>
            </div>
            <div style={{ marginBottom: 20 }}>
              <FLabel palette={palette}>연락처 (선택)</FLabel>
              <FInput value={phone} onChange={setPhone} placeholder="010-0000-0000" palette={palette} />
            </div>
            <div style={{ marginBottom: 24 }}>
              <FLabel palette={palette}>특별히 여쭙고 싶은 것이 있다면</FLabel>
              <textarea value={question} onChange={(e) => setQuestion(e.target.value)} rows={4}
                placeholder={isGunghap ? '예) 결혼을 앞두고 있는데 두 사람의 합이 어떤지 궁금합니다.' : '예) 올해 직장 운이 어떨지, 이직을 고민하고 있습니다.'}
                style={{ width: '100%', padding: '12px 14px', fontSize: 14, fontFamily: 'Nanum Myeongjo, serif', background: palette.paper, border: `1px solid ${palette.line}`, color: palette.ink, outline: 'none', resize: 'vertical', boxSizing: 'border-box', lineHeight: 1.6 }} />
            </div>
            <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: 13, color: palette.ink, marginBottom: 24, cursor: 'pointer', lineHeight: 1.6 }}>
              <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} style={{ marginTop: 3, accentColor: palette.accent }} />
              <span>개인정보 수집 및 이용에 동의합니다. 입력하신 정보는 풀이 목적 외에는 사용되지 않으며, 결과 전달 후 30일 뒤 파기됩니다.</span>
            </label>
            <button onClick={() => validateStep1() && setStep(2)} disabled={!validateStep1()} style={{ width: '100%', padding: '16px', fontSize: 15, fontFamily: 'Nanum Myeongjo, serif', fontWeight: 700, background: validateStep1() ? palette.ink : palette.line, color: palette.paper, border: 'none', cursor: validateStep1() ? 'pointer' : 'not-allowed', letterSpacing: '0.1em' }}>
              결제 단계로 넘어가기 →
            </button>
          </div>
        )}

        {/* Step 2: 결제 */}
        {step === 2 && (
          <div>
            <div style={{ background: 'rgba(168, 51, 42, 0.05)', border: `1px solid ${palette.line}`, padding: '20px 24px', marginBottom: 24 }}>
              <div style={{ fontSize: 13, color: palette.muted, marginBottom: 12, letterSpacing: '0.05em' }}>주문 내역</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
                <span style={{ fontSize: 17, fontWeight: 700 }}>{title}</span>
                <span style={{ fontSize: 14, color: palette.muted, textDecoration: 'line-through' }}>{fmt(original)}원</span>
              </div>
              <div style={{ fontSize: 13, color: palette.muted, lineHeight: 1.7, marginBottom: 16 }}>
                {isGunghap ? '두 분의 사주를 함께 풀어 합과 흐름을 살펴드립니다.' : '한 사람의 사주를 깊이 풀어 평생의 흐름을 살펴드립니다.'}
              </div>
              <_Divider width={300} color={palette.ink} opacity={0.25} />
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 14 }}>
                <span style={{ fontSize: 13, color: palette.muted }}>개업 기념 할인가</span>
                <span style={{ fontSize: 24, fontWeight: 700, color: palette.accent, letterSpacing: '0.02em' }}>{fmt(price)}원</span>
              </div>
            </div>

            {/* 결제 안내 */}
            <div style={{ padding: '18px 20px', background: 'rgba(31,26,20,0.03)', border: `1px solid ${palette.line}`, marginBottom: 22, fontSize: 13, color: palette.inkSoft, lineHeight: 1.9 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                  <rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/>
                </svg>
                <span style={{ fontWeight: 700, fontSize: 14 }}>토스페이먼츠 결제</span>
              </div>
              신용카드 · 체크카드로 결제하실 수 있습니다.<br />
              결제 버튼을 누르시면 토스페이먼츠 결제창으로 이동합니다.
            </div>

            {/* 에러 메시지 */}
            {payError && (
              <div style={{ marginBottom: 16, padding: '12px 16px', background: 'rgba(168,51,42,0.08)', border: `1px solid ${palette.accent}`, fontSize: 13, color: palette.accent, lineHeight: 1.7 }}>
                {payError}
              </div>
            )}

            <div style={{ display: 'flex', gap: 10 }}>
              <button onClick={() => { setStep(1); setPayError(''); }} style={{ flex: '0 0 auto', padding: '16px 24px', fontSize: 14, fontFamily: 'Nanum Myeongjo, serif', background: 'transparent', color: palette.ink, border: `1px solid ${palette.line}`, cursor: 'pointer', letterSpacing: '0.05em' }}>← 이전</button>
              <button onClick={handlePayment} disabled={processing} style={{ flex: 1, padding: '16px', fontSize: 15, fontFamily: 'Nanum Myeongjo, serif', fontWeight: 700, background: '#3182f6', color: '#fff', border: 'none', cursor: processing ? 'wait' : 'pointer', letterSpacing: '0.05em', opacity: processing ? 0.75 : 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
                {processing ? (
                  <>
                    <span style={{ display: 'inline-block', width: 16, height: 16, border: '2px solid rgba(255,255,255,0.4)', borderTopColor: '#fff', borderRadius: '50%', animation: 'spin 0.8s linear infinite' }} />
                    결제 처리 중…
                  </>
                ) : (
                  <>{fmt(price)}원 · 토스페이먼츠로 결제</>
                )}
              </button>
            </div>
            <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
          </div>
        )}

        {/* Step 3: 완료 */}
        {step === 3 && (
          <div style={{ textAlign: 'center', padding: '20px 0 10px' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
              <_Seal text="白楊" size={88} color={palette.accent} />
            </div>
            <h3 style={{ fontFamily: '"Gaegu", "Nanum Brush Script", serif', fontSize: 32, fontWeight: 400, margin: '0 0 12px', letterSpacing: '0.05em' }}>잘 받았습니다</h3>

            <p style={{ fontSize: 15, lineHeight: 1.9, color: palette.ink, margin: '0 auto 24px', maxWidth: 380 }}>
              결제가 완료되었습니다.<br />
              영업일 기준 <b>2~3일 안에</b> 풀이를 마쳐<br />
              <b style={{ color: palette.accent }}>{email}</b> 으로<br />
              결과지를 보내드리겠습니다.
            </p>

            <div style={{ background: 'rgba(168,51,42,0.04)', border: `1px dashed ${palette.line}`, padding: '18px 22px', textAlign: 'left', marginBottom: 24, fontSize: 13, lineHeight: 1.8, color: palette.ink }}>
              <div style={{ color: palette.muted, fontSize: 12, marginBottom: 6, letterSpacing: '0.05em' }}>주문 번호</div>
              <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 10, fontFamily: 'monospace', letterSpacing: '0.05em' }}>
                {orderNumber}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '4px 12px', fontSize: 12, color: palette.muted }}>
                <span>결제</span><span>토스페이먼츠 · 완료</span>
                <span>이메일</span><span>{email}</span>
                {phone && <><span>연락처</span><span>{phone}</span></>}
              </div>
              <div style={{ marginTop: 12, paddingTop: 10, borderTop: `1px solid ${palette.line}`, color: palette.muted, fontSize: 12 }}>
                결과지 도착이 늦어지면 {CONFIG.ADMIN_EMAIL} 으로 연락 주십시오.
              </div>
            </div>
            <button onClick={onClose} style={{ padding: '14px 36px', fontSize: 14, fontFamily: 'Nanum Myeongjo, serif', background: palette.ink, color: palette.paper, border: 'none', cursor: 'pointer', letterSpacing: '0.15em' }}>
              처음으로 돌아가기
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

// ─── 문의 모달 ─────────────────────────────────────────────

const InquiryModal = ({ palette, onClose }) => {
  const [name, setName] = useStateFlow('');
  const [email, setEmail] = useStateFlow('');
  const [phone, setPhone] = useStateFlow('');
  const [topic, setTopic] = useStateFlow('');
  const [message, setMessage] = useStateFlow('');
  const [agree, setAgree] = useStateFlow(false);
  const [sent, setSent] = useStateFlow(false);
  const [submitting, setSubmitting] = useStateFlow(false);

  const canSubmit = name.trim() && (email.trim() || phone.trim()) && message.trim().length >= 10 && agree && !submitting;

  const topicLabels = {
    before: '풀이 시작 전 궁금한 점', during: '진행 중인 풀이 문의',
    after: '풀이 받은 후 추가 질문', schedule: '일정 변경·연기',
    refund: '환불·결제', other: '그 외', '': '미선택',
  };

  const submit = async () => {
    if (!canSubmit) return;
    setSubmitting(true);
    const inquiryId = 'INQ-' + Date.now();

    // localStorage 저장 (관리자 페이지 연동)
    try {
      const inbox = JSON.parse(localStorage.getItem('baekyangdang_inquiries') || '[]');
      inbox.unshift({ id: inquiryId, name, email, phone, topic, message, createdAt: new Date().toISOString(), status: 'unread' });
      localStorage.setItem('baekyangdang_inquiries', JSON.stringify(inbox.slice(0, 50)));
    } catch (_) {}

    // EmailJS 발송
    if (window.emailjs && CONFIG.EMAILJS_PUBLIC_KEY !== 'YOUR_EMAILJS_PUBLIC_KEY') {
      try {
        await emailjs.send(CONFIG.EMAILJS_SERVICE_ID, CONFIG.EMAILJS_INQUIRY_TEMPLATE, {
          inquiry_id:   inquiryId,
          name,
          email:        email || '-',
          phone:        phone || '-',
          topic:        topicLabels[topic] || topic,
          message,
          admin_email:  CONFIG.ADMIN_EMAIL,
          submitted_at: new Date().toLocaleString('ko-KR'),
        });
      } catch (e) {
        console.warn('[백양당] 문의 EmailJS 발송 실패:', e);
      }
    }

    setSent(true);
    setSubmitting(false);
  };

  useEffectFlow(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div role="dialog" aria-modal="true" aria-labelledby="inquiry-title" onClick={onClose}
      style={{ position: 'fixed', inset: 0, zIndex: 100, background: 'rgba(20, 18, 16, 0.55)', backdropFilter: 'blur(2px)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '60px 16px 40px', overflowY: 'auto' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: '100%', maxWidth: 540, background: palette.paper, backgroundImage: `url("${_HANJI}")`, border: `1px solid ${palette.line}`, padding: '40px 36px 36px', fontFamily: 'Nanum Myeongjo, serif', color: palette.ink, position: 'relative', boxShadow: '0 30px 60px -20px rgba(20,18,16,0.4)' }}>
        <button onClick={onClose} aria-label="닫기" style={{ position: 'absolute', top: 14, right: 14, width: 36, height: 36, background: 'transparent', border: 'none', fontSize: 22, color: palette.muted, cursor: 'pointer', fontFamily: 'serif', lineHeight: 1 }}>×</button>

        {!sent ? (
          <>
            <div style={{ textAlign: 'center', marginBottom: 28 }}>
              <div style={{ fontSize: 11, letterSpacing: '0.4em', color: palette.muted, marginBottom: 10 }}>문 의 하 기</div>
              <h3 id="inquiry-title" style={{ fontFamily: '"Gaegu", "Nanum Brush Script", serif', fontSize: 28, fontWeight: 400, margin: 0, lineHeight: 1.4 }}>편하게 적어 주십시오</h3>
              <p style={{ fontSize: 13, color: palette.inkSoft, margin: '14px auto 0', maxWidth: 380, lineHeight: 1.8 }}>
                풀이 전후의 궁금증 · 일정 조율 · 환불 문의 등<br />무엇이든 좋습니다. 평일 1~2일 안에 답해 드립니다.
              </p>
            </div>
            <div style={{ display: 'grid', gap: 14 }}>
              <div>
                <FLabel palette={palette} required>성함</FLabel>
                <FInput value={name} onChange={setName} placeholder="홍길동" palette={palette} />
              </div>
              <div>
                <FLabel palette={palette}>이메일</FLabel>
                <FInput value={email} onChange={setEmail} placeholder="name@email.com" type="email" palette={palette} />
              </div>
              <div>
                <FLabel palette={palette}>전화번호</FLabel>
                <FInput value={phone} onChange={setPhone} placeholder="010-0000-0000" type="tel" palette={palette} />
                <div style={{ fontSize: 11, color: palette.muted, marginTop: 4 }}>이메일 또는 전화번호 중 적어도 하나는 적어 주십시오</div>
              </div>
              <div>
                <FLabel palette={palette}>문의 종류</FLabel>
                <FSelect value={topic} onChange={setTopic}
                  options={[{ value: '', label: '선택 안 함' }, { value: 'before', label: '풀이 시작 전 궁금한 점' }, { value: 'during', label: '진행 중인 풀이 문의' }, { value: 'after', label: '풀이 받은 후 추가 질문' }, { value: 'schedule', label: '일정 변경 · 연기' }, { value: 'refund', label: '환불 · 결제' }, { value: 'other', label: '그 외' }]}
                  palette={palette} />
              </div>
              <div>
                <FLabel palette={palette} required>남기실 말씀</FLabel>
                <textarea value={message} onChange={(e) => setMessage(e.target.value)}
                  placeholder="자세히 적어 주실수록 정확한 답을 드릴 수 있습니다 (10자 이상)" rows={5}
                  style={{ width: '100%', resize: 'vertical', minHeight: 120, padding: '12px 14px', fontSize: 16, fontFamily: 'Nanum Myeongjo, serif', background: palette.paper, border: `1px solid ${palette.line}`, borderRadius: 0, color: palette.ink, outline: 'none', boxSizing: 'border-box', lineHeight: 1.7 }} />
                <div style={{ fontSize: 11, color: palette.muted, textAlign: 'right', marginTop: 4 }}>{message.length} / 1000</div>
              </div>
              <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: 13, color: palette.inkSoft, cursor: 'pointer', padding: '10px 0', lineHeight: 1.6 }}>
                <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} style={{ marginTop: 4, accentColor: palette.accent }} />
                <span>
                  답변을 위해 위 연락처로 회신받는 것에 동의합니다.<br />
                  <span style={{ color: palette.muted, fontSize: 11 }}>수집된 연락처는 답변 후 30일 내 파기됩니다.</span>
                </span>
              </label>
              <button onClick={submit} disabled={!canSubmit} style={{ marginTop: 8, padding: '16px', fontSize: 15, fontWeight: 600, fontFamily: 'Nanum Myeongjo, serif', background: canSubmit ? palette.ink : palette.line, color: canSubmit ? palette.paper : palette.muted, border: 'none', borderRadius: 0, cursor: canSubmit ? 'pointer' : 'not-allowed', letterSpacing: '0.25em', transition: 'background 0.2s', opacity: submitting ? 0.7 : 1 }}>
                {submitting ? '보내는 중…' : '보 내 기'}
              </button>
            </div>
          </>
        ) : (
          <div style={{ textAlign: 'center', padding: '20px 0 8px' }}>
            <div style={{ fontSize: 11, letterSpacing: '0.4em', color: palette.accent, marginBottom: 14 }}>접 수 완 료</div>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 20 }}>
              <_CloudMotif size={80} color={palette.accent} opacity={0.5} />
            </div>
            <h3 style={{ fontFamily: '"Gaegu", "Nanum Brush Script", serif', fontSize: 30, fontWeight: 400, margin: 0, lineHeight: 1.4 }}>잘 받았습니다</h3>
            <p style={{ fontSize: 14, color: palette.inkSoft, margin: '20px auto 32px', maxWidth: 360, lineHeight: 2.0 }}>
              적어 주신 연락처로 답을 드리겠습니다.<br />
              평일 1~2일 안에 답해 드리되, 길어지더라도 반드시 회신 드립니다.
            </p>
            <div style={{ borderTop: `1px solid ${palette.line}`, paddingTop: 20, marginTop: 8, display: 'grid', gap: 6, fontSize: 12, color: palette.muted }}>
              <div>접수번호 · INQ-{Date.now().toString().slice(-6)}</div>
              <div>접수시각 · {new Date().toLocaleString('ko-KR', { dateStyle: 'long', timeStyle: 'short' })}</div>
            </div>
            <button onClick={onClose} style={{ marginTop: 32, padding: '14px 40px', fontSize: 14, fontWeight: 600, fontFamily: 'Nanum Myeongjo, serif', background: 'transparent', color: palette.ink, border: `1px solid ${palette.ink}`, borderRadius: 0, cursor: 'pointer', letterSpacing: '0.25em' }}>닫 기</button>
          </div>
        )}
      </div>
    </div>
  );
};

window.__flow = { ServiceFlow, InquiryModal };



const { useState: useStateLanding } = React;

const {
  PalgwaeCircle: _PalgwaeCircle, CloudMotif: _LCloudMotif, FlowerMotif: _FlowerMotif,
  ZodiacRing: _LZodiacRing, Taegeuk: _LTaegeuk, Seal: _LSeal, Divider: _LDivider,
  HANJI_TEXTURE_DATA_URL: _LHANJI,
} = window.__patterns;
const { ServiceFlow: _ServiceFlow, InquiryModal: _InquiryModal } = window.__flow;

// ─── 팔레트 ───────────────────────────────────────────────
const PALETTE = {
  paper: '#f4ecd8',
  paperDeep: '#ebe1c9',
  ink: '#1f1a14',
  inkSoft: '#3a322a',
  muted: '#8a7d68',
  line: 'rgba(31, 26, 20, 0.18)',
  accent: '#a8332a',
};

// ─── 공통 ─────────────────────────────────────────────────
const SectionLabel = ({ children }) => (
  <div className="section-label" style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 12, letterSpacing: '0.4em', color: PALETTE.accent, marginBottom: 14 }}>
    {children}
  </div>
);

const SectionTitle = ({ children, size = 38, id }) => (
  <h2 id={id} className="section-title" style={{ fontFamily: '"Gaegu", "Nanum Brush Script", "Nanum Myeongjo", serif', fontSize: size, fontWeight: 400, lineHeight: 1.3, color: PALETTE.ink, margin: 0, letterSpacing: '0.02em' }}>
    {children}
  </h2>
);

// ─── Hero ─────────────────────────────────────────────────
const Hero = ({ onSaju, onGunghap }) => {
  const headline = '사주 여덟 글자에\n사람의 결을 풀어 드립니다';
  const subline = '예순이 다 되어가다 보니, 이제야 역술에 대해서 조금 알 것 같습니다.\n오랜 시간 사람의 사주를 마주해 온 마음으로 정성껏 풀어 보내 드리겠습니다.';
  const HIGHLIGHT = '바람은 정해져 있어도 돛은 우리가 답니다.';
  const raw = headline;
  const idx = raw.indexOf(HIGHLIGHT);
  const main = idx >= 0 ? raw.slice(0, idx).replace(/\s+$/, '') : raw;
  const tail = idx >= 0 ? raw.slice(idx + HIGHLIGHT.length).replace(/^\s+/, '') : '';

  return (
    <section id="hero" className="hero-section" aria-label="히어로—백양당 사주 궁합 풀이 소개"
      style={{ padding: '90px 64px 100px', position: 'relative', background: PALETTE.paper, backgroundImage: `url("${_LHANJI}")`, borderBottom: `1px solid ${PALETTE.line}`, overflow: 'hidden' }}>
      <div className="hero-bg-decor" style={{ position: 'absolute', top: -60, right: -100, opacity: 0.10, pointerEvents: 'none' }}>
        <_PalgwaeCircle size={520} color={PALETTE.ink} opacity={1} />
      </div>
      <div className="hero-cloud-decor" style={{ position: 'absolute', top: 30, left: 40, opacity: 0.25 }}>
        <_LCloudMotif size={160} color={PALETTE.ink} opacity={1} />
      </div>

      <div style={{ position: 'relative', maxWidth: 760, margin: '0 auto', textAlign: 'center' }}>
        <div className="hero-shopname" style={{ fontFamily: 'Noto Serif KR, serif', fontSize: 14, letterSpacing: '0.6em', color: PALETTE.muted, marginBottom: 18 }}>
          白 楊 堂
        </div>
        <div className="hero-tagline" style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 13, letterSpacing: '0.3em', color: PALETTE.accent, marginBottom: 36 }}>
          역 술 인 · 사 주 · 궁 합
        </div>

        <div style={{ margin: '0 0 28px' }}>
          {main && (
            <h1 className="hero-headline-main" style={{ fontFamily: '"Nanum Myeongjo", "Noto Serif KR", serif', fontSize: 32, fontWeight: 700, lineHeight: 1.6, color: PALETTE.ink, margin: '0 0 22px', letterSpacing: '0.01em', wordBreak: 'keep-all' }}>
              {main}
            </h1>
          )}
          {idx >= 0 && (
            <div className="hero-headline-highlight" style={{ fontFamily: '"Gaegu", "Nanum Brush Script", serif', fontSize: 56, fontWeight: 700, lineHeight: 1.35, color: PALETTE.accent, letterSpacing: '0.02em', wordBreak: 'keep-all', textShadow: '0 1px 0 rgba(255,255,255,0.4)' }}>
              {HIGHLIGHT}
            </div>
          )}
          {tail && (
            <h1 className="hero-headline-tail" style={{ fontFamily: '"Nanum Myeongjo", "Noto Serif KR", serif', fontSize: 32, fontWeight: 700, lineHeight: 1.6, color: PALETTE.ink, margin: '22px 0 0', letterSpacing: '0.01em', wordBreak: 'keep-all' }}>
              {tail}
            </h1>
          )}
        </div>

        <_LDivider width={120} color={PALETTE.ink} opacity={0.4} />

        <p className="hero-subline" style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 17, lineHeight: 2.0, color: PALETTE.inkSoft, margin: '28px auto 48px', maxWidth: 560, whiteSpace: 'pre-line' }}>
          {subline}
        </p>

        <div className="hero-cta-row" style={{ display: 'flex', gap: 16, justifyContent: 'center', flexWrap: 'wrap' }}>
          <button onClick={onSaju} className="hero-cta" style={{ padding: '20px 44px', fontSize: 16, fontFamily: 'Nanum Myeongjo, serif', fontWeight: 700, background: PALETTE.ink, color: PALETTE.paper, border: 'none', cursor: 'pointer', letterSpacing: '0.18em', minWidth: 220 }}>
            사주풀이 보기 →
          </button>
          <button onClick={onGunghap} className="hero-cta" style={{ padding: '20px 44px', fontSize: 16, fontFamily: 'Nanum Myeongjo, serif', fontWeight: 700, background: 'transparent', color: PALETTE.accent, border: `1px solid ${PALETTE.accent}`, cursor: 'pointer', letterSpacing: '0.18em', minWidth: 220 }}>
            궁합풀이 보기 →
          </button>
        </div>

        <div className="hero-price-note" style={{ marginTop: 28, fontSize: 13, color: PALETTE.muted, fontFamily: 'Nanum Myeongjo, serif', letterSpacing: '0.05em' }}>
          - 온라인 개업 기념 할인 이벤트 중 -
        </div>
      </div>
    </section>
  );
};

// ─── 역술인 소개 ───────────────────────────────────────────
const MasterIntro = () => (
  <section id="about" className="master-section" aria-labelledby="about-title"
    style={{ padding: '100px 64px', background: PALETTE.paper, backgroundImage: `url("${_LHANJI}")`, borderBottom: `1px solid ${PALETTE.line}` }}>
    <div className="master-grid" style={{ maxWidth: 920, margin: '0 auto', display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 72, alignItems: 'flex-start' }}>
      <div className="master-left" style={{ textAlign: 'center', position: 'sticky', top: 80 }}>
        <div className="master-seal" style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
          <_LSeal text="白楊" size={88} color={PALETTE.accent} />
        </div>
        <div style={{ fontFamily: 'Noto Serif KR, serif', fontSize: 28, letterSpacing: '0.3em', color: PALETTE.ink, marginBottom: 8 }}>白楊堂</div>
        <div style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 14, color: PALETTE.muted, letterSpacing: '0.1em' }}>백양당</div>
        <div style={{ marginTop: 28, paddingTop: 20, borderTop: `1px solid ${PALETTE.line}`, fontSize: 12, color: PALETTE.muted, lineHeight: 1.8, fontFamily: 'Nanum Myeongjo, serif' }}>
          역술 30여 년<br />정통 명리학 · 자미두수
        </div>
      </div>

      <div className="master-body-wrap">
        <SectionLabel>역 술 인 의 말</SectionLabel>
        <h2 id="about-title" className="master-title" style={{ fontFamily: '"Gaegu", "Nanum Brush Script", "Nanum Myeongjo", serif', fontSize: 40, fontWeight: 400, lineHeight: 1.3, color: PALETTE.ink, margin: 0, letterSpacing: '0.02em' }}>
          예순이 되어서야<br />조금 알 것 같습니다
        </h2>
        <div className="master-body" style={{ marginTop: 36, fontFamily: 'Nanum Myeongjo, serif', fontSize: 16, lineHeight: 2.1, color: PALETTE.inkSoft }}>
          <p style={{ margin: '0 0 24px' }}>
            예순이 다 되어가다 보니 이제야 역술에 대해서 조금 알 것 같습니다. 젊을 적엔
            책 속 글자만 좇아 사주를 풀었고, 마흔 즈음엔 사람을 본다 자신했지요. 그러다
            오십을 넘기고서야, 사람의 삶이란 사주 여덟 글자에 다 담길 만큼 가벼운 것이
            아니라는 걸 알았습니다.
          </p>
          <p style={{ margin: '0 0 24px' }}>
            사주는 정해진 운명을 알려주는 것이 아닙니다. 타고난 기운의 결을 읽고,
            그 결을 따라 어디에 힘을 주고 어디에 힘을 빼야 할지 살펴 드리는 일입니다.
            바람이 불어올 때 돛을 어디에 두는지에 따라 배의 방향이 달라지듯이요.
          </p>
          <p style={{ margin: '0 0 24px' }}>
            저를 찾아오시는 분들께는 늘 같은 말씀을 드립니다. 운명을 점치러 오지
            마시고, 자신을 들여다보러 오십시오. 풀이는 거울일 뿐입니다. 길을 걷는 건
            결국 본인이십니다.
          </p>
          <p className="master-sign" style={{ margin: '32px 0 0', textAlign: 'right', fontFamily: '"Gaegu", "Nanum Brush Script", serif', fontSize: 22, color: PALETTE.ink, letterSpacing: '0.05em' }}>
            — 백양당 주인 드림
          </p>
        </div>
      </div>
    </div>
  </section>
);

// ─── 서비스 카드 ───────────────────────────────────────────
const ServiceCard = ({ kind, onOpen }) => {
  const isSaju = kind === 'saju';
  const data = isSaju ? {
    title: '사주풀이', hanja: '四 柱', subtitle: '한 사람의 결을 읽다',
    body: '태어난 해, 달, 날, 시 — 네 기둥에 담긴 기운을 풀어 평생의 흐름과 올해·내년의 운세, 직업·재물·건강의 결을 살펴드립니다.',
    items: ['평생 사주 — 명조와 격국, 용신 풀이', '올해와 내년의 흐름 — 세운(歲運) 풀이', '직업·재물·인간관계 — 십신(十神)으로 본 결', '주의해야 할 시기와 도움이 되는 방향'],
    original: 30000, price: 25000,
    symbol: <_LZodiacRing size={140} color={PALETTE.ink} accent={PALETTE.accent} />,
  } : {
    title: '궁합풀이', hanja: '宮 合', subtitle: '두 사람의 결을 맞대다',
    body: '두 분의 사주를 함께 펴놓고 서로의 기운이 어떻게 만나는지, 어디서 부딪히고 어디서 채워주는지 정성껏 살펴드립니다.',
    items: ['두 사람의 사주 비교 — 일주(日柱) 합·충', '관계의 기본 흐름 — 서로에게 미치는 영향', '결혼·연애의 시기와 길한 방향', '함께 풀어야 할 과제와 보완하는 길'],
    original: 50000, price: 40000,
    symbol: (
      <div style={{ position: 'relative', width: 140, height: 140 }}>
        <div style={{ position: 'absolute', left: 8, top: 20 }}><_LTaegeuk size={80} color1={PALETTE.accent} color2={PALETTE.ink} stroke={PALETTE.ink} /></div>
        <div style={{ position: 'absolute', right: 8, top: 40 }}><_LTaegeuk size={80} color1={PALETTE.ink} color2={PALETTE.accent} stroke={PALETTE.ink} /></div>
      </div>
    ),
  };

  return (
    <div className="service-card" style={{ background: PALETTE.paper, backgroundImage: `url("${_LHANJI}")`, border: `1px solid ${PALETTE.line}`, padding: '44px 44px 40px', position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <div style={{ position: 'absolute', top: 14, right: 14 }}>
        <_FlowerMotif size={28} color={PALETTE.accent} opacity={0.35} />
      </div>
      <div style={{ fontFamily: 'Noto Serif KR, serif', fontSize: 22, letterSpacing: '0.3em', color: PALETTE.muted, marginBottom: 12 }}>{data.hanja}</div>
      <h3 style={{ fontFamily: '"Gaegu", "Nanum Brush Script", serif', fontSize: 44, fontWeight: 400, margin: '0 0 8px', color: PALETTE.ink }}>{data.title}</h3>
      <div style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 14, color: PALETTE.accent, letterSpacing: '0.1em', marginBottom: 24 }}>{data.subtitle}</div>
      <div className="service-card-symbol" style={{ display: 'flex', justifyContent: 'center', margin: '8px 0 24px' }}>{data.symbol}</div>
      <p className="service-card-body" style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 15, lineHeight: 2.0, color: PALETTE.inkSoft, margin: '0 0 24px' }}>{data.body}</p>
      <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 32px', fontFamily: 'Nanum Myeongjo, serif', fontSize: 14, lineHeight: 1.8, color: PALETTE.ink }}>
        {data.items.map((it, i) => (
          <li key={i} style={{ padding: '10px 0', borderBottom: i < data.items.length - 1 ? `1px dashed ${PALETTE.line}` : 'none', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <span style={{ color: PALETTE.accent, fontSize: 12, marginTop: 4 }}>◆</span>
            <span>{it}</span>
          </li>
        ))}
      </ul>
      <div style={{ marginTop: 'auto' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', paddingBottom: 16, borderBottom: `1px solid ${PALETTE.line}`, marginBottom: 16 }}>
          <div>
            <div style={{ fontSize: 12, color: PALETTE.muted, fontFamily: 'Nanum Myeongjo, serif', marginBottom: 4, letterSpacing: '0.1em' }}>개업 기념 할인가</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
              <span style={{ fontSize: 14, color: PALETTE.muted, textDecoration: 'line-through', fontFamily: 'Nanum Myeongjo, serif' }}>{data.original.toLocaleString()}원</span>
              <span className="service-card-price" style={{ fontSize: 30, color: PALETTE.accent, fontWeight: 700, fontFamily: 'Nanum Myeongjo, serif' }}>
                {data.price.toLocaleString()}<span style={{ fontSize: 16, marginLeft: 2 }}>원</span>
              </span>
            </div>
          </div>
        </div>
        <button onClick={onOpen} className="service-card-cta" style={{ width: '100%', padding: '16px', fontSize: 15, fontFamily: 'Nanum Myeongjo, serif', fontWeight: 700, background: isSaju ? PALETTE.ink : PALETTE.accent, color: PALETTE.paper, border: 'none', cursor: 'pointer', letterSpacing: '0.15em' }}>
          {data.title} 신청하기 →
        </button>
      </div>
    </div>
  );
};

const Services = ({ onSaju, onGunghap }) => (
  <section id="services" className="services-section" aria-labelledby="services-title"
    style={{ padding: '100px 64px', background: PALETTE.paperDeep, backgroundImage: `url("${_LHANJI}")`, borderBottom: `1px solid ${PALETTE.line}` }}>
    <div style={{ maxWidth: 1080, margin: '0 auto' }}>
      <div style={{ textAlign: 'center', marginBottom: 56 }}>
        <SectionLabel>풀 이 서 비 스</SectionLabel>
        <SectionTitle id="services-title">두 가지 풀이로 모십니다</SectionTitle>
        <p style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 15, color: PALETTE.muted, margin: '20px auto 0', maxWidth: 520, lineHeight: 1.9 }}>
          가벼이 보고 가시는 일이 아니라, 한 사람 한 사람의 사주를 펴놓고 한 자 한 자 짚어가며 풀어 드립니다.
        </p>
      </div>
      <div className="services-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }}>
        <ServiceCard kind="saju" onOpen={onSaju} />
        <ServiceCard kind="gunghap" onOpen={onGunghap} />
      </div>
    </div>
  </section>
);

// ─── 이용 절차 ─────────────────────────────────────────────
const Process = () => {
  const steps = [
    { hanja: '一', title: '정보 입력', body: '풀이를 받으실 분의 성함과 생년월일·시, 결과지를 받으실 메일 주소를 적어 주십시오.' },
    { hanja: '二', title: '결제', body: '카드, 카카오페이, 계좌이체 중 편하신 방법으로 결제해 주십시오. 영수증은 메일로 함께 보내드립니다.' },
    { hanja: '三', title: '풀이 작성', body: '주신 사주를 정성껏 펴 놓고, 손으로 한 자 한 자 풀어 적습니다. 기계로 뽑아내는 결과가 아닙니다.' },
    { hanja: '四', title: 'PDF 수령', body: '영업일 기준 2~3일 안에 풀이가 담긴 PDF 파일을 메일로 보내드립니다. 천천히 읽어 보십시오.' },
  ];
  return (
    <section id="process" className="process-section" aria-labelledby="process-title"
      style={{ padding: '100px 64px', background: PALETTE.paper, backgroundImage: `url("${_LHANJI}")`, borderBottom: `1px solid ${PALETTE.line}` }}>
      <div style={{ maxWidth: 1080, margin: '0 auto' }}>
        <div style={{ textAlign: 'center', marginBottom: 64 }}>
          <SectionLabel>이 용 절 차</SectionLabel>
          <SectionTitle id="process-title">이렇게 받아보십니다</SectionTitle>
        </div>
        <div className="process-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, position: 'relative' }}>
          <div className="process-line" style={{ position: 'absolute', top: 38, left: '12.5%', right: '12.5%', borderTop: `1px dashed ${PALETTE.line}`, zIndex: 0 }} />
          {steps.map((s, i) => (
            <div key={i} style={{ textAlign: 'center', padding: '0 16px', position: 'relative', zIndex: 1 }}>
              <div className="process-step-circle" style={{ width: 76, height: 76, borderRadius: '50%', background: PALETTE.paper, border: `1.5px solid ${PALETTE.accent}`, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 22px', fontFamily: 'Noto Serif KR, serif', fontSize: 30, color: PALETTE.accent, fontWeight: 600 }}>
                {s.hanja}
              </div>
              <h4 className="process-step-title" style={{ fontFamily: '"Gaegu", "Nanum Brush Script", serif', fontSize: 26, fontWeight: 400, margin: '0 0 12px', color: PALETTE.ink }}>{s.title}</h4>
              <p className="process-step-body" style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 14, lineHeight: 1.9, color: PALETTE.inkSoft, margin: 0 }}>{s.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ─── 가격 안내 ─────────────────────────────────────────────
const Pricing = ({ onSaju, onGunghap }) => (
  <section id="pricing" className="pricing-section" aria-labelledby="pricing-title"
    style={{ padding: '100px 64px', background: PALETTE.paperDeep, backgroundImage: `url("${_LHANJI}")`, borderBottom: `1px solid ${PALETTE.line}` }}>
    <div style={{ maxWidth: 720, margin: '0 auto', textAlign: 'center' }}>
      <SectionLabel>가 격 안 내</SectionLabel>
      <SectionTitle id="pricing-title">개업 기념 할인 중입니다</SectionTitle>
      <p style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 15, color: PALETTE.muted, margin: '20px auto 48px', lineHeight: 1.9, maxWidth: 480 }}>
        오래 인터넷에 둥지를 트지 못하다 이제야 자리 잡아 모십니다.<br />
        그 인사로 한동안은 할인된 값으로 풀어 드립니다.
      </p>
      <div className="pricing-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, background: PALETTE.line }}>
        {[
          { kind: 'saju', name: '사주풀이', original: 30000, price: 25000, onClick: onSaju },
          { kind: 'gunghap', name: '궁합풀이', original: 50000, price: 40000, onClick: onGunghap },
        ].map((p) => (
          <div key={p.kind} className="pricing-card" style={{ padding: '36px 28px', background: PALETTE.paper, backgroundImage: `url("${_LHANJI}")`, textAlign: 'center' }}>
            <div className="pricing-card-name" style={{ fontFamily: '"Gaegu", "Nanum Brush Script", serif', fontSize: 30, color: PALETTE.ink, marginBottom: 16 }}>{p.name}</div>
            <div style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 14, color: PALETTE.muted, textDecoration: 'line-through', marginBottom: 4 }}>{p.original.toLocaleString()}원</div>
            <div className="pricing-card-price" style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 38, fontWeight: 700, color: PALETTE.accent, marginBottom: 22 }}>{p.price.toLocaleString()}원</div>
            <button onClick={p.onClick} style={{ padding: '12px 28px', fontSize: 14, fontFamily: 'Nanum Myeongjo, serif', background: 'transparent', color: PALETTE.ink, border: `1px solid ${PALETTE.ink}`, cursor: 'pointer', letterSpacing: '0.1em' }}>
              신청하기 →
            </button>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 32, fontFamily: 'Nanum Myeongjo, serif', fontSize: 13, color: PALETTE.muted, lineHeight: 1.8 }}>
        결과지는 PDF로 보내드립니다 · 영업일 기준 2~3일 소요 · 부가세 포함
      </div>
    </div>
  </section>
);

// ─── 상담 문의 ─────────────────────────────────────────────
const Contact = ({ onInquiry }) => (
  <section id="contact" className="contact-section" aria-labelledby="contact-title"
    style={{ padding: '90px 64px 100px', background: PALETTE.paper, backgroundImage: `url("${_LHANJI}")` }}>
    <div style={{ maxWidth: 760, margin: '0 auto', textAlign: 'center' }}>
      <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
        <_LCloudMotif size={120} color={PALETTE.ink} opacity={0.3} />
      </div>
      <SectionLabel>상 담 · 문 의</SectionLabel>
      <SectionTitle id="contact-title">여쭙고 싶은 게 있으시면</SectionTitle>
      <p style={{ fontFamily: 'Nanum Myeongjo, serif', fontSize: 16, color: PALETTE.inkSoft, margin: '24px auto 40px', lineHeight: 2.0, maxWidth: 520 }}>
        풀이 전후로 궁금한 점이 있으시면 편하게 연락 주십시오.<br />
        급하지 않으시면 메일로 적어 보내 주시는 편이 가장 좋습니다.
      </p>
      <div className="contact-grid" style={{ display: 'inline-grid', gridTemplateColumns: 'auto auto', gap: '14px 36px', fontFamily: 'Nanum Myeongjo, serif', fontSize: 15, color: PALETTE.ink, textAlign: 'left', padding: '28px 40px', border: `1px solid ${PALETTE.line}`, background: 'rgba(168, 51, 42, 0.03)' }}>
        <span style={{ color: PALETTE.muted }}>메 일</span>
        <span style={{ fontWeight: 600 }}>by4lucky@gmail.com</span>
        <span style={{ color: PALETTE.muted }}>응 답</span>
        <span>평일 오전 10시 ~ 오후 6시</span>
      </div>
      <div style={{ marginTop: 32 }}>
        <button onClick={onInquiry} aria-label="백양당에 글로 문의하기"
          onMouseEnter={(e) => { e.currentTarget.style.background = PALETTE.accent; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = PALETTE.ink; }}
          style={{ padding: '16px 44px', fontFamily: 'Nanum Myeongjo, serif', fontSize: 15, fontWeight: 600, background: PALETTE.ink, color: PALETTE.paper, border: 'none', borderRadius: 0, cursor: 'pointer', letterSpacing: '0.25em', transition: 'background 0.2s' }}>
          글 로  문 의 하 기
        </button>
        <div style={{ marginTop: 12, fontFamily: 'Nanum Myeongjo, serif', fontSize: 12, color: PALETTE.muted, letterSpacing: '0.05em' }}>전화가 어려우시면 글로 남겨 주십시오 · 평일 1~2일 안에 답해 드립니다</div>
      </div>
      <div style={{ marginTop: 56, paddingTop: 32, borderTop: `1px solid ${PALETTE.line}`, fontFamily: 'Nanum Myeongjo, serif', fontSize: 12, color: PALETTE.muted, lineHeight: 1.9, letterSpacing: '0.05em' }}>
        백양당 · 白楊堂 · 사주 · 궁합 풀이<br />
        © 백양당. 본 사이트의 풀이는 참고용이며, 의학·법률·재정의 전문적 판단을 대체하지 않습니다.
      </div>
    </div>
  </section>
);

// ─── 결제 완료/실패 오버레이 ───────────────────────────────
const PaymentResultOverlay = ({ result, onClose }) => {
  const isSuccess = result.status === 'success';
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 2000, background: 'rgba(26,26,26,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>
      <div style={{ width: '100%', maxWidth: 480, background: PALETTE.paper, border: `1px solid ${PALETTE.line}`, padding: '48px 40px 40px', textAlign: 'center', fontFamily: 'Nanum Myeongjo, serif', color: PALETTE.ink, boxShadow: '0 30px 80px rgba(0,0,0,0.25)' }}>
        {isSuccess ? (
          <>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
              <_LSeal text="白楊" size={80} color={PALETTE.accent} />
            </div>
            <h2 style={{ fontFamily: '"Gaegu","Nanum Brush Script",serif', fontSize: 30, fontWeight: 400, margin: '0 0 16px' }}>잘 받았습니다</h2>
            <p style={{ fontSize: 15, lineHeight: 1.9, color: PALETTE.inkSoft, margin: '0 auto 28px', maxWidth: 340 }}>
              결제가 완료되었습니다.<br />
              영업일 기준 <b>2~3일 안에</b> 풀이를 마쳐<br />
              이메일로 결과지를 보내드리겠습니다.
            </p>
            <div style={{ padding: '14px 18px', background: 'rgba(168,51,42,0.04)', border: `1px dashed ${PALETTE.line}`, fontSize: 12, color: PALETTE.muted, marginBottom: 28, textAlign: 'left', lineHeight: 1.8 }}>
              <div style={{ marginBottom: 4 }}>주문번호 · <b style={{ fontFamily: 'monospace', color: PALETTE.ink }}>{result.orderId}</b></div>
              <div>문의 · {result.adminEmail || 'by4lucky@gmail.com'}</div>
            </div>
          </>
        ) : (
          <>
            <div style={{ fontSize: 36, marginBottom: 16 }}>⚠️</div>
            <h2 style={{ fontFamily: '"Gaegu","Nanum Brush Script",serif', fontSize: 28, fontWeight: 400, margin: '0 0 14px' }}>결제가 완료되지 않았습니다</h2>
            <p style={{ fontSize: 14, lineHeight: 1.9, color: PALETTE.inkSoft, margin: '0 auto 28px', maxWidth: 340 }}>
              {result.message || '결제가 취소되었거나 오류가 발생했습니다.'}<br />
              다시 시도해 주십시오.
            </p>
          </>
        )}
        <button onClick={onClose} style={{ padding: '14px 40px', fontSize: 14, fontFamily: 'Nanum Myeongjo, serif', background: PALETTE.ink, color: PALETTE.paper, border: 'none', cursor: 'pointer', letterSpacing: '0.15em' }}>
          {isSuccess ? '처음으로 돌아가기' : '닫 기'}
        </button>
      </div>
    </div>
  );
};

// ─── 앱 루트 ───────────────────────────────────────────────
const { useEffect: useEffectLanding } = React;

function App() {
  const [flow, setFlow] = useStateLanding(null);
  const [showInquiry, setShowInquiry] = useStateLanding(false);
  const [paymentResult, setPaymentResult] = useStateLanding(null); // { status, orderId, message }

  // 토스페이먼츠 리다이렉트 결과 처리
  useEffectLanding(() => {
    const params = new URLSearchParams(location.search);
    const payment = params.get('payment');
    const orderId = params.get('orderId');
    if (!payment || !orderId) return;

    // URL 즉시 정리
    history.replaceState({}, '', location.pathname);

    if (payment === 'success') {
      // sessionStorage에서 주문 데이터 복원 후 저장
      try {
        const raw = sessionStorage.getItem('by_pending_order');
        if (raw) {
          const order = JSON.parse(raw);
          // localStorage에 주문 영구 저장
          const orders = JSON.parse(localStorage.getItem('baekyangdang_orders') || '[]');
          orders.unshift({
            order_num: orderId, service: order.service, price: order.price + '원',
            name1: order.person1?.name, gender1: order.person1?.gender,
            birth1: `${order.person1?.year}년 ${order.person1?.month}월 ${order.person1?.day}일`,
            name2: order.isGunghap ? order.person2?.name : '-',
            customer_email: order.email, customer_phone: order.phone || '-',
            question: order.question || '없음', pay_method: '토스페이먼츠',
            pay_status: '결제 완료', admin_email: 'by4lucky@gmail.com',
            createdAt: new Date().toISOString(), status: 'paid',
          });
          localStorage.setItem('baekyangdang_orders', JSON.stringify(orders.slice(0, 200)));
          sessionStorage.removeItem('by_pending_order');

          // EmailJS 발송 (설정된 경우)
          const cfg = window.__CONFIG__;
          if (window.emailjs && cfg && cfg.EMAILJS_PUBLIC_KEY !== 'YOUR_EMAILJS_PUBLIC_KEY') {
            emailjs.send(cfg.EMAILJS_SERVICE_ID, cfg.EMAILJS_ADMIN_TEMPLATE, orders[0]).catch(() => {});
          }
        }
      } catch (_) {}
      setPaymentResult({ status: 'success', orderId });
    } else if (payment === 'fail') {
      const msg = params.get('message') || '결제가 취소되었습니다.';
      setPaymentResult({ status: 'fail', orderId, message: decodeURIComponent(msg) });
    }
  }, []);

  return (
    <div>
      <main itemScope itemType="https://schema.org/LocalBusiness" aria-label="백양당 사주풀이 궁합풀이 안내"
        style={{ background: PALETTE.paperDeep, color: PALETTE.ink, minHeight: '100%' }}>
        <meta itemProp="name" content="백양당" />
        <meta itemProp="alternateName" content="白楊堂" />
        <meta itemProp="priceRange" content="₩25,000 ~ ₩40,000" />
        <Hero onSaju={() => setFlow('saju')} onGunghap={() => setFlow('gunghap')} />
        <MasterIntro />
        <Services onSaju={() => setFlow('saju')} onGunghap={() => setFlow('gunghap')} />
        <Process />
        <Pricing onSaju={() => setFlow('saju')} onGunghap={() => setFlow('gunghap')} />
        <Contact onInquiry={() => setShowInquiry(true)} />
      </main>

      {showInquiry && (
        <_InquiryModal palette={PALETTE} onClose={() => setShowInquiry(false)} />
      )}
      {flow && (
        <_ServiceFlow service={flow} onClose={() => setFlow(null)} palette={PALETTE} />
      )}
      {paymentResult && (
        <PaymentResultOverlay result={paymentResult} onClose={() => setPaymentResult(null)} />
      )}
    </div>
  );
}

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


