// phone-scroll.jsx — scroll-driven 3D card reveal with an Instagram-DM iPhone
// mockup as the screen. Vanilla scroll progress (no framer-motion).
//
// Layout: a tall section. As the user scrolls through it, the phone tilts
// from rotateX(22deg) -> rotateX(0deg) and scales subtly. The title block
// translates upward in lockstep.

function useScrollProgress(ref) {
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf = 0;
    const update = () => {
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight;
      // 0 when the section's top hits the bottom of viewport.
      // 1 when the section's bottom hits the top of viewport.
      const total = r.height + vh;
      const passed = vh - r.top;
      const raw = passed / total;
      setP(Math.max(0, Math.min(1, raw)));
    };
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(update);
    };
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      cancelAnimationFrame(raf);
    };
  }, [ref]);
  return p;
}

function PhoneScrollSection() {
  const ref = React.useRef(null);
  const p = useScrollProgress(ref);
  const m = useIsMobile();

  // remap progress: tilt unfolds between 0.0..0.55 of section
  const k = Math.max(0, Math.min(1, (p - 0.05) / 0.55));
  const rotate = 22 - 22 * k; // 22deg → 0deg
  const scale = 0.95 + 0.05 * k; // 0.95 → 1.0
  const titleY = -120 * k; // translate title up as we scroll in

  return (
    <section
      ref={ref}
      style={{
        position: 'relative',
        padding: m ? '10px 12px 48px' : '20px 64px 60px',
        minHeight: m ? 1040 : 1300,
        overflow: 'hidden'
      }}>
      
      {/* Compact lead-in (big headline lives in the CTA above) */}
      <div
        style={{
          position: 'relative',
          maxWidth: 1280,
          width: '100%',
          margin: '0 auto',
          textAlign: 'center',
          transform: `translateY(${titleY}px)`,
          willChange: 'transform', padding: m ? '40px 0 0' : '100px 0px 0px'
        }}>
        
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 10,

          borderRadius: 999,
          border: '1px solid var(--line-2)',
          background: 'rgba(12,14,18,0.5)',
          fontSize: 13, color: 'var(--fg-2)', height: "40px", padding: "8px 19px 8px 10px", width: "276px", lineHeight: "1.42", fontWeight: "500", borderWidth: "1px"
        }}>
          <span style={{
            width: 22, height: 22, borderRadius: '50%',
            background: 'conic-gradient(from 180deg, #feda77, #f58529, #dd2a7b, #8134af, #515bd4, #feda77)',
            display: 'inline-block', flexShrink: 0
          }} />
          ответьте на 6 вопросов в директе
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#3ad27a' }} />
        </div>
      </div>

      {/* Sticky phone */}
      <div
        style={{
          position: 'sticky',
          top: m ? 70 : 90,
          margin: '40px auto 0',
          width: 'fit-content',
          perspective: '1400px'
        }}>
        
        <div
          style={{
            transform: `rotateX(${rotate}deg) scale(${(m ? 0.8 : 1) * scale})`,
            transformOrigin: '50% 0%',
            transition: 'transform 0s linear',
            willChange: 'transform'
          }}>
          
          <PhoneFrame>
            <InstagramDM />
          </PhoneFrame>
        </div>
      </div>
    </section>);

}

/* ----- Phone frame -------------------------------------------------------- */
function PhoneFrame({ children }) {
  return (
    <div
      style={{
        position: 'relative',
        width: 420,
        height: 860,
        borderRadius: 56,
        padding: 12,
        background: 'linear-gradient(180deg, #2a2e35 0%, #15181d 100%)',
        boxShadow:
        '0 0 0 1px rgba(255,255,255,0.06) inset,' +
        '0 80px 120px rgba(0,0,0,0.55),' +
        '0 30px 60px rgba(0,0,0,0.35),' +
        '0 0 0 1px rgba(0,0,0,0.4)'
      }}>
      
      {/* Screen */}
      <div
        style={{
          position: 'relative',
          width: '100%', height: '100%',
          borderRadius: 44,
          overflow: 'hidden',
          background: '#000',
          boxShadow: '0 0 0 1px rgba(0,0,0,0.6) inset'
        }}>
        
        {/* Dynamic Island */}
        <div
          style={{
            position: 'absolute',
            top: 12,
            left: '50%',
            transform: 'translateX(-50%)',
            width: 118,
            height: 34,
            borderRadius: 22,
            background: '#000',
            zIndex: 10
          }} />
        
        {children}
      </div>
      {/* Side buttons */}
      <span style={{ position: 'absolute', left: -2, top: 130, width: 4, height: 32, background: '#15181d', borderRadius: 2 }} />
      <span style={{ position: 'absolute', left: -2, top: 200, width: 4, height: 62, background: '#15181d', borderRadius: 2 }} />
      <span style={{ position: 'absolute', left: -2, top: 280, width: 4, height: 62, background: '#15181d', borderRadius: 2 }} />
      <span style={{ position: 'absolute', right: -2, top: 220, width: 4, height: 90, background: '#15181d', borderRadius: 2 }} />
    </div>);

}

/* ----- Instagram DM screen — INTERACTIVE FORM ----------------------------- */
const DM_FLOW = [
{ id: 'intro', text: 'Привет! Это xaydarov.a1 👋 Давайте быстро обсудим проект — шесть коротких вопросов.' },
{ id: 'name', text: 'Как вас зовут?', placeholder: 'Имя...' },
{ id: 'niche', text: 'Какая у вас ниша?', placeholder: 'Например: недвижимость, ресторан…' },
{ id: 'agency', text: 'Работали ли вы с SMM-агентством раньше?',
  choices: ['Да, работали', 'Нет, впервые'] },
{ id: 'pain', text: 'Какие были трудности?', placeholder: 'Кратко в 1–2 предложениях…' },
{ id: 'sales', text: 'Готовы получать продажи через соцсети? :)',
  choices: ['Да, готов', 'Хочу обсудить'] },
{ id: 'contact', text: 'Оставьте username в Telegram или номер телефона.', placeholder: '@username или +998...' },
{ id: 'done', text: 'Заявка получена 🙏 Вернёмся с диагностикой и стратегией роста в течение суток.' }];

const DM_QUESTIONS = 6;

/* ----- Lead submission ---------------------------------------------------
   Set ONE of these to enable real delivery:
   • FORMSPREE_ENDPOINT — create a free form at formspree.io, paste its URL.
   • TG_BOT_TOKEN + TG_CHAT_ID — your Telegram bot token and chat id.
   Until configured, leads are saved to localStorage ('akmal_lead') as backup. */
const FORMSPREE_ENDPOINT = ''; // e.g. 'https://formspree.io/f/abcdwxyz'
const TG_BOT_TOKEN = '8796078612:AAFv_6663dq2gXckiEzibSCfdvB1kn2L8xg';
const TG_CHAT_ID = '342199159';

const DM_LABELS = {
  name: 'Имя', niche: 'Ниша', agency: 'Опыт с агентством',
  pain: 'Трудности', sales: 'Готовность к продажам', contact: 'Контакт'
};

async function sendLead(answers) {
  const lines = Object.keys(DM_LABELS)
    .filter((k) => answers[k])
    .map((k) => `${DM_LABELS[k]}: ${answers[k]}`);
  const text = '🟦 Новая заявка с сайта\n\n' + lines.join('\n');
  try { localStorage.setItem('akmal_lead', JSON.stringify({ ...answers, ts: Date.now() })); } catch (e) {}

  // Analytics: count this as a conversion (Vercel + Yandex Metrica if present)
  try {
    if (window.va) window.va('event', { name: 'lead_submitted' });
    if (window.ym && window.__YM_ID) window.ym(window.__YM_ID, 'reachGoal', 'lead');
  } catch (e) {}

  try {
    if (FORMSPREE_ENDPOINT) {
      await fetch(FORMSPREE_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({ ...answers, _subject: 'Заявка с сайта Акмаля' })
      });
    } else if (TG_BOT_TOKEN && TG_CHAT_ID) {
      await fetch(`https://api.telegram.org/bot${TG_BOT_TOKEN}/sendMessage`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ chat_id: TG_CHAT_ID, text })
      });
    }
  } catch (e) { /* swallow — UI already confirms; lead is in localStorage */ }
}


function InstagramDM() {
  const [messages, setMessages] = React.useState([
  { from: 'bot', text: DM_FLOW[0].text },
  { from: 'bot', text: DM_FLOW[1].text }]
  );
  const [qIdx, setQIdx] = React.useState(1); // current question awaiting answer
  const [input, setInput] = React.useState('');
  const [answers, setAnswers] = React.useState({});
  const chatRef = React.useRef(null);

  React.useEffect(() => {
    if (chatRef.current) chatRef.current.scrollTop = chatRef.current.scrollHeight;
  }, [messages]);

  const current = DM_FLOW[qIdx];
  const isDone = !current || current.id === 'done';

  const submit = (value) => {
    if (!value || !value.trim() || isDone) return;
    const v = value.trim();
    const nextAnswers = { ...answers, [current.id]: v };
    setAnswers(nextAnswers);
    const next = DM_FLOW[qIdx + 1];
    setMessages((m) => {
      const out = [...m, { from: 'user', text: v }];
      if (next) out.push({ from: 'bot', text: next.text });
      return out;
    });
    // 'contact' is the final question → fire the lead off.
    if (current.id === 'contact') sendLead(nextAnswers);
    setQIdx(qIdx + 1);
    setInput('');
  };

  const showChoices = !!current?.choices && !isDone;

  return (
    <div style={{
      position: 'relative',
      width: '100%', height: '100%',
      background: '#000',
      color: '#f4f1ec',
      fontFamily: 'Onest, system-ui, sans-serif',
      display: 'flex', flexDirection: 'column'
    }}>
      {/* iOS status bar */}
      <div style={{
        height: 54,
        padding: '14px 32px 0',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        fontSize: 15, fontWeight: 600, color: '#fff'
      }}>
        <span>14:32</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <svg width="17" height="11" viewBox="0 0 17 11" fill="#fff">
            <rect x="0" y="7" width="3" height="4" rx="0.7" />
            <rect x="4.5" y="5" width="3" height="6" rx="0.7" />
            <rect x="9" y="2.5" width="3" height="8.5" rx="0.7" />
            <rect x="13.5" y="0" width="3" height="11" rx="0.7" />
          </svg>
          <svg width="15" height="11" viewBox="0 0 15 11" fill="none">
            <path d="M7.5 1.5C5 1.5 2.7 2.4 1 3.9" stroke="#fff" strokeWidth="1.4" strokeLinecap="round" />
            <path d="M7.5 5C6 5 4.6 5.5 3.5 6.5" stroke="#fff" strokeWidth="1.4" strokeLinecap="round" />
            <circle cx="7.5" cy="9" r="1.3" fill="#fff" />
            <path d="M14 3.9c-1.7-1.5-4-2.4-6.5-2.4" stroke="#fff" strokeWidth="1.4" strokeLinecap="round" />
            <path d="M11.5 6.5c-1.1-1-2.5-1.5-4-1.5" stroke="#fff" strokeWidth="1.4" strokeLinecap="round" />
          </svg>
          <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 1 }}>
            <div style={{ width: 24, height: 11, borderRadius: 3, border: '1px solid rgba(255,255,255,0.4)', padding: 1 }}>
              <div style={{ width: '78%', height: '100%', background: '#fff', borderRadius: 1 }} />
            </div>
            <div style={{ width: 1.5, height: 4, background: 'rgba(255,255,255,0.4)', borderRadius: '0 1px 1px 0' }} />
          </div>
        </div>
      </div>

      {/* DM Header */}
      <div style={{
        padding: '12px 16px',
        borderBottom: '1px solid rgba(255,255,255,0.08)',
        display: 'grid', gridTemplateColumns: 'auto 1fr auto',
        alignItems: 'center', gap: 12, flexShrink: 0
      }}>
        <button style={{ background: 'transparent', border: 0, padding: 0, color: '#fff', display: 'flex' }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="m15 18-6-6 6-6" />
          </svg>
        </button>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
          <div style={{
            width: 36, height: 36, borderRadius: '50%', padding: 2,
            background: 'conic-gradient(from 180deg, #feda77, #f58529, #dd2a7b, #8134af, #515bd4, #feda77)'
          }}>
            <div style={{ width: '100%', height: '100%', borderRadius: '50%', background: '#000', padding: 2 }}>
              <div style={{
                width: '100%', height: '100%', borderRadius: '50%',
                background: 'linear-gradient(135deg, #2a3344 0%, #5b8bff 100%)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontWeight: 700, fontSize: 13, color: '#fff'
              }}>А</div>
            </div>
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ fontSize: 15, fontWeight: 600 }}>xaydarov.a1</span>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="#5b8bff">
                <path d="M12 2 9 5l-4 .2L4.6 9 2 12l2.6 3 .4 3.8L9 19l3 3 3-3 4-.2.4-3.8L22 12l-2.6-3-.4-3.8L15 5z" />
                <path d="m9 12 2 2 4-4" stroke="#000" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <div style={{
              fontSize: 11,
              color: isDone ? '#3ad27a' : 'rgba(244,241,236,0.5)',
              marginTop: 1,
              display: 'flex', alignItems: 'center', gap: 5
            }}>
              {isDone ? <>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#3ad27a' }} />
                заявка получена
              </> : 'в сети · отвечает в течение часа'}
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 16, color: '#fff' }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" />
          </svg>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <polygon points="23 7 16 12 23 17 23 7" />
            <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />
          </svg>
        </div>
      </div>

      {/* Chat body */}
      <div
        ref={chatRef}
        style={{
          flex: 1,
          overflowY: 'auto',
          padding: '14px 12px 8px',
          display: 'flex', flexDirection: 'column', gap: 6,
          scrollbarWidth: 'none'
        }}>
        
        <div style={{
          alignSelf: 'center', fontSize: 11,
          color: 'rgba(244,241,236,0.45)', margin: '4px 0 14px',
          letterSpacing: '0.04em'
        }}>Сегодня · 14:32</div>

        {messages.map((m, i) => <Bubble key={i} from={m.from}>{m.text}</Bubble>)}
        {/* Progress hint */}
        {!isDone &&
        <div style={{
          alignSelf: 'flex-start',
          marginTop: 6,
          fontSize: 10,
          color: 'rgba(244,241,236,0.35)',
          fontFamily: 'JetBrains Mono, monospace',
          letterSpacing: '0.06em'
        }}>
            {qIdx} / {DM_QUESTIONS} · ответьте, чтобы продолжить
          </div>
        }
      </div>

      {/* Quick-reply chips (when current question has choices) */}
      {showChoices &&
      <div style={{
        padding: '6px 12px 8px',
        display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'flex-end'
      }}>
          {current.choices.map((c) =>
        <button key={c} onClick={() => submit(c)} style={{
          padding: '8px 14px',
          borderRadius: 999,
          border: '1px solid rgba(91,139,255,0.45)',
          background: 'rgba(91,139,255,0.12)',
          color: '#cbd9ff',
          fontSize: 13, fontWeight: 500,
          fontFamily: 'inherit'
        }}>{c}</button>
        )}
        </div>
      }

      {/* Input bar */}
      <div style={{
        padding: '8px 12px 28px',
        display: 'flex', alignItems: 'center', gap: 8,
        borderTop: '1px solid rgba(255,255,255,0.04)'
      }}>
        <button style={{
          width: 38, height: 38, borderRadius: '50%',
          background: '#5b8bff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: 0, flexShrink: 0
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" />
            <circle cx="12" cy="13" r="4" />
          </svg>
        </button>

        <form
          onSubmit={(e) => {e.preventDefault();submit(input);}}
          style={{
            flex: 1, height: 38,
            background: 'rgba(255,255,255,0.06)',
            border: '1px solid rgba(255,255,255,0.08)',
            borderRadius: 22,
            display: 'flex', alignItems: 'center',
            padding: '0 6px 0 14px', gap: 8
          }}>
          
          <input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            disabled={isDone || showChoices}
            placeholder={
            isDone ? 'Заявка отправлена' :
            showChoices ? 'Выберите бюджет ↑' :
            current?.placeholder || 'Сообщение...'
            }
            style={{
              flex: 1,
              border: 0, outline: 0, background: 'transparent',
              color: '#f4f1ec',
              fontSize: 14, fontFamily: 'inherit'
            }} />
          
          {input.trim() && !showChoices && !isDone ?
          <button type="submit" style={{
            padding: '6px 14px', borderRadius: 999,
            background: 'transparent', color: '#5b8bff',
            fontSize: 14, fontWeight: 700, border: 0,
            fontFamily: 'inherit'
          }}>Отпр.</button> :

          <span style={{ display: 'flex', gap: 8, padding: '0 8px 0 0' }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="rgba(244,241,236,0.7)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12V7a7 7 0 0 1 14 0v5" />
                <path d="M3 12h18l-2 7H5z" />
              </svg>
            </span>
          }
        </form>

        <button style={{
          width: 38, height: 38, borderRadius: '50%',
          background: 'transparent',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: 0, flexShrink: 0
        }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#5b8bff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <rect x="9" y="3" width="6" height="11" rx="3" />
            <path d="M5 11a7 7 0 0 0 14 0M12 18v3M9 21h6" />
          </svg>
        </button>
      </div>

      {/* Home indicator */}
      <div style={{
        position: 'absolute', bottom: 8, left: '50%',
        transform: 'translateX(-50%)',
        width: 134, height: 5, borderRadius: 3, background: '#fff'
      }} />

      <style>{`
        @keyframes ig-msg-in {
          from { opacity: 0; transform: translateY(8px); }
          to   { opacity: 1; transform: none; }
        }
      `}</style>
    </div>);

}

function Bubble({ from, children }) {
  const isBot = from === 'bot';
  return (
    <div
      style={{
        alignSelf: isBot ? 'flex-start' : 'flex-end',
        maxWidth: '78%',
        padding: '9px 14px',
        borderRadius: 22,
        ...(isBot ?
        { background: '#262a31', color: '#f4f1ec', borderBottomLeftRadius: 6 } :
        { background: 'linear-gradient(135deg, #5b8bff 0%, #3b6cff 100%)', color: '#fff', borderBottomRightRadius: 6 }),
        fontSize: 14,
        lineHeight: 1.35,
        animation: 'ig-msg-in .28s cubic-bezier(.2,.7,.2,1)',
        wordBreak: 'break-word'
      }}>
      
      {children}
    </div>);

}

window.PhoneScrollSection = PhoneScrollSection;
window.InstagramDM = InstagramDM;
window.PhoneFrame = PhoneFrame;