/* ============================================================
   bezikaron — корень приложения: маршрутизация экранов,
   мобильная оболочка с масштабированием, Tweaks.
   ============================================================ */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "violet",
  "headingFont": "Rubik",
  "bodyFont": "Rubik",
  "warmBg": false
}/*EDITMODE-END*/;

const ACCENTS = {
  violet: { '--accent': '#6D4AFF', '--accent-deep': '#5A36E6', '--accent-tint': '#ECE8FF', '--on-accent': '#FFFFFF' },
  sage:   { '--accent': '#7C8B7A', '--accent-deep': '#5E6D5D', '--accent-tint': '#E7EAE3', '--on-accent': '#FBFAF6' },
  bronze: { '--accent': '#A8895C', '--accent-deep': '#8A6E43', '--accent-tint': '#EEE6D8', '--on-accent': '#FBFAF6' },
};

function useScale(w, h) {
  const [scale, setScale] = React.useState(1);
  React.useEffect(() => {
    const fit = () => {
      const padW = window.innerWidth < 520 ? 0 : 48;
      const padH = window.innerWidth < 520 ? 0 : 48;
      setScale(Math.min(1, (window.innerWidth - padW) / w, (window.innerHeight - padH) / h));
    };
    fit();
    window.addEventListener('resize', fit);
    return () => window.removeEventListener('resize', fit);
  }, [w, h]);
  return scale;
}

function useIsPhone() {
  const get = () => window.innerWidth <= 520;
  const [phone, setPhone] = React.useState(get);
  React.useEffect(() => {
    const f = () => setPhone(get());
    window.addEventListener('resize', f);
    return () => window.removeEventListener('resize', f);
  }, []);
  return phone;
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const phone = useIsPhone();

  // экран-оверлей поверх вкладок: 'main' | 'checkout' | 'processing' | 'confirm'
  const [view, setView] = React.useState('main');
  const [tab, setTab] = React.useState('home');
  const [checkout, setCheckout] = React.useState({ mode: 'order' });
  const [lastOrder, setLastOrder] = React.useState(null);
  const [confirmOrder, setConfirmOrder] = React.useState(null);
  const W = 402, H = 874;
  const scale = useScale(W, H);

  const openOrder = (pkgId, monument) => { setCheckout({ mode: 'order', pkg: pkgId, monument, preselected: !!pkgId }); setView('checkout'); };
  const openSub = (tier, period, monument) => { setCheckout({ mode: 'subscribe', subTier: tier, plan: period, monument, preselected: !!tier }); setView('checkout'); };
  const goTab = (id) => { setView('main'); setTab(id); };
  const closeCheckout = () => setView('main');

  const MANAGERS = [{ name: 'אנה לוריא', role: 'מנהל טיפול אישי' }, { name: 'דוד כץ', role: 'מנהל טיפול אישי' }];
  const finishCheckout = (raw) => {
    const now = new Date();
    const order = {
      ...raw,
      id: String(100000 + Math.floor(Math.random() * 900000)),
      createdAt: now.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' }),
      manager: MANAGERS[Math.floor(Math.random() * MANAGERS.length)],
    };
    setLastOrder(order);
    setConfirmOrder(order);
    setView('processing');
    setTimeout(() => setView('confirm'), 1500);
  };

  // стиль-обёртка с активными токенами
  const themeVars = {
    ...ACCENTS[t.accent] || ACCENTS.violet,
    '--font-head': `'${t.headingFont}', 'Frank Ruhl Libre', Georgia, serif`,
    '--font-body': `'${t.bodyFont}', 'Heebo', system-ui, sans-serif`,
    '--bg': t.warmBg ? '#F6F5FA' : '#FFFFFF',
  };

  const isMain = view === 'main';
  const statusDark = isMain && tab === 'cabinet' && !!lastOrder;
  const NAV_PAD = 92; // место под нижнюю навигацию

  const inner = isMain ? (
    <div style={{ position: 'relative', height: '100%', background: 'var(--bg)' }}>
      <div key={tab} className="no-scrollbar fade-up" style={{ position: 'absolute', inset: 0, overflowY: 'auto' }}>
        <div style={{ minHeight: '100%', paddingBottom: NAV_PAD }}>
          {tab === 'home' && <Landing onOrder={openOrder} lastOrder={lastOrder} onCabinet={() => goTab('cabinet')} />}
          {tab === 'care' && <CareScreen onOrder={openOrder} onGoSub={() => goTab('sub')} />}
          {tab === 'sub' && <SubscriptionScreen onSubscribe={openSub} />}
          {tab === 'cabinet' && (lastOrder
            ? <Cabinet order={lastOrder} onHome={() => goTab('home')} />
            : <CabinetEmpty onGoCare={() => goTab('care')} />)}
        </div>
      </div>
      <BottomNav tab={tab} onTab={goTab} hasOrder={!!lastOrder} />
    </div>
  ) : (
    <div className="no-scrollbar" style={{ height: '100%', overflowY: view === 'confirm' ? 'auto' : 'hidden', background: 'var(--bg)' }}>
      {view === 'checkout' && (
        <Checkout
          mode={checkout.mode}
          initialPackage={checkout.pkg}
          initialPlan={checkout.plan}
          initialSubTier={checkout.subTier}
          initialMonument={checkout.monument}
          preselected={checkout.preselected}
          onClose={closeCheckout}
          onDone={finishCheckout}
        />
      )}
      {view === 'processing' && <Processing mode={checkout.mode} />}
      {view === 'confirm' && <Confirmation order={confirmOrder} onHome={() => goTab('home')} onSubscribe={() => goTab('sub')} onCabinet={() => goTab('cabinet')} />}
    </div>
  );

  return (
    <React.Fragment>
      {phone ? (
        // ── телефон: на весь экран, без рамки-макета ──
        <div style={{ position: 'fixed', inset: 0, overflow: 'hidden', background: 'var(--bg)', ...themeVars }}>
          {inner}
        </div>
      ) : (
        // ── десктоп: в iOS-фрейме по центру ──
        <div style={{ minHeight: '100vh', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#d9d4ca' }}>
          <div style={{ width: W * scale, height: H * scale, flexShrink: 0 }}>
            <div style={{ width: W, height: H, transform: `scale(${scale})`, transformOrigin: 'top left', ...themeVars }}>
              <IOSDevice width={W} height={H} statusDark={statusDark}>
                {inner}
              </IOSDevice>
            </div>
          </div>
        </div>
      )}

      <TweaksPanel>
        <TweakSection label="צבע הדגשה" />
        <TweakRadio label="צבע הכפתורים" value={t.accent}
          options={[{ value: 'violet', label: 'Tending' }, { value: 'sage', label: 'מרווה' }, { value: 'bronze', label: 'ברונזה' }]}
          onChange={(v) => setTweak('accent', v)} />
        <TweakColor label="תצוגה מקדימה" value={ACCENTS[t.accent] ? ACCENTS[t.accent]['--accent'] : '#6D4AFF'}
          options={['#6D4AFF', '#7C8B7A', '#A8895C']}
          onChange={(v) => setTweak('accent', v === '#6D4AFF' ? 'violet' : v === '#7C8B7A' ? 'sage' : 'bronze')} />

        <TweakSection label="טיפוגרפיה" />
        <TweakRadio label="כותרות" value={t.headingFont}
          options={['Rubik', 'Heebo', 'Libre Baskerville']}
          onChange={(v) => setTweak('headingFont', v)} />
        <TweakRadio label="טקסט" value={t.bodyFont}
          options={['Rubik', 'Heebo', 'Poppins']}
          onChange={(v) => setTweak('bodyFont', v)} />

        <TweakSection label="רקע" />
        <TweakToggle label="לבן חמים" value={t.warmBg} onChange={(v) => setTweak('warmBg', v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

// ---------- Переход к оплате ----------
function Processing({ mode }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 22, padding: 40, background: 'var(--bg)' }}>
      <div className="spin" style={{
        width: 56, height: 56, borderRadius: 999,
        border: '3px solid var(--accent-tint)', borderTopColor: 'var(--accent)',
      }} />
      <div style={{ textAlign: 'center' }}>
        <h2 className="t-h3" style={{ marginBottom: 8 }}>מעבירים אתכם לתשלום מאובטח</h2>
        <p className="t-small">pay.bezikaron · החיבור מאובטח</p>
      </div>
    </div>
  );
}

// ---------- Подтверждение ----------
function Confirmation({ order, onHome, onSubscribe, onCabinet }) {
  const D = window.DATA;
  const isSub = order.mode === 'subscribe';
  const pkg = D.packages.find((p) => p.id === order.pkg);
  const subPrice = isSub ? window.PRICE.sub(order.monument, order.subTier, order.plan) : null;
  const orderPrice = !isSub && pkg ? window.PRICE.pkg(pkg.id, order.monument) : 0;
  const needsContact = order.placeMethod === 'help' || order.placeMethod === 'photo';
  const subFrom = window.PRICE.sub(order.monument || 'single', 'basic', 'month').monthlyBase;

  const timeline = isSub
    ? [
        { icon: 'mail', title: 'אישור למייל', desc: 'נשלח את פרטי המנוי והתנאים.' },
        { icon: 'pin', title: 'הביקור הראשון — ברבעון הקרוב', desc: 'המנהל יתאם מועד נוח.' },
        { icon: 'camera', title: 'דוח תמונות אחרי כל ביקור', desc: 'תוכלו לראות את המצב כל השנה.' },
      ]
    : [
        needsContact
          ? { icon: 'phone', title: 'מנהל יצור קשר היום', desc: 'נוודא מקום ופרטים — ברוגע, בלי לחץ.' }
          : { icon: 'check', title: 'ההזמנה הועברה לבעל המקצוע', desc: 'הכל ברור, אין צורך להתקשר.' },
        { icon: 'pin', title: 'נבצע תוך 5–7 ימים', desc: 'נטפל בקבר בקפידה.' },
        { icon: 'camera', title: 'נשלח דוח עם תמונות', desc: 'תמונות "לפני ואחרי" — תראו הכל.' },
      ];

  return (
    <div style={{ background: 'var(--bg)', minHeight: '100%' }}>
      {/* верхняя зона */}
      <div style={{ paddingTop: 78, paddingInline: 24, paddingBottom: 30, textAlign: 'center' }}>
        <div className="pop" style={{
          width: 76, height: 76, borderRadius: 999, margin: '0 auto 20px',
          background: 'var(--accent)', color: 'var(--on-accent)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 10px 30px color-mix(in oklch, var(--accent) 40%, transparent)',
        }}><Icon name="check" size={38} stroke={2.4} /></div>
        <h1 className="t-h2" style={{ marginBottom: 10 }}>{isSub ? 'המנוי הופעל' : 'ההזמנה התקבלה'}</h1>
        <p className="t-lead" style={{ maxWidth: 320, margin: '0 auto' }}>
          {isSub
            ? 'תודה על האמון. מעכשיו נשמור על הזיכרון כל השנה.'
            : 'תודה. נטפל בכל בקפידה ונעדכן אתכם.'}
        </p>
      </div>

      {/* что дальше */}
      <div style={{ padding: '0 22px 24px' }}>
        <div className="card" style={{ padding: 22 }}>
          <div className="t-eyebrow" style={{ marginBottom: 18 }}>מה הצעדים הבאים</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {timeline.map((s, i) => (
              <div key={i} style={{ display: 'flex', gap: 14 }}>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                  <IconDisc name={s.icon} size={44} />
                  {i < timeline.length - 1 && <div style={{ width: 1.5, flex: 1, background: 'var(--line)', minHeight: 18 }} />}
                </div>
                <div style={{ paddingBottom: i < timeline.length - 1 ? 18 : 0, paddingTop: 8 }}>
                  <h3 className="t-h3" style={{ fontSize: 17, marginBottom: 3 }}>{s.title}</h3>
                  <p className="t-small">{s.desc}</p>
                </div>
              </div>
            ))}
          </div>
          <div className="divider" style={{ margin: '6px 0 16px' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span className="t-small">{isSub ? D.subscription.title : pkg.name}</span>
            <span style={{ fontWeight: 700 }}>{isSub ? `${window.fmt(subPrice.perMonth)} ₪/חודש` : `${window.fmt(orderPrice)} ₪`}</span>
          </div>
        </div>
      </div>

      {/* мягкая допродажа подписки (только для разового) */}
      {!isSub && (
        <div style={{ padding: '0 22px 24px' }}>
          <div className="card" style={{ padding: 20, background: 'var(--accent-tint)', border: '1px solid color-mix(in oklch, var(--accent) 28%, transparent)' }}>
            <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
              <IconDisc name="leaf" size={44} />
              <div style={{ flex: 1 }}>
                <h3 className="t-h3" style={{ fontSize: 18, marginBottom: 6 }}>רוצים שנשמור על זה כל השנה?</h3>
                <p className="t-small" style={{ marginBottom: 14 }}>בלי מעורבות שלכם: טיפול אחת לרבעון ודוחות תמונות. החל מ-{window.fmt(subFrom)} ₪/חודש. ללא התחייבות.</p>
                <button className="btn btn-ghost btn-sm" style={{ width: '100%' }} onClick={() => onSubscribe()}>מידע על המנוי</button>
              </div>
            </div>
          </div>
        </div>
      )}

      <div style={{ padding: '0 22px 40px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <button className="btn btn-primary" onClick={onCabinet}>
          מעקב אחר ההזמנה באזור האישי
          <Icon name="arrow" size={20} stroke={2} />
        </button>
        <button className="btn btn-quiet" onClick={onHome}>
          <Icon name="arrowL" size={18} /> חזרה לדף הבית
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { App, Processing, Confirmation });

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