// The Fone Shop — Camera Quote (Pillar 1 — the moat)
// Full-viewport sheet on mobile, centered card on desktop. One flow, four states.
const { useState, useEffect, useRef } = React;

const Eyebrow = ({ children, style }) => (
  <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: '0.2em', color: '#86868b', textTransform: 'uppercase', ...style }}>{children}</div>
);

// ------ photo slot (faux damaged-phone illustration) ------
const PhotoSlot = ({ filled, onClick, idx, tone = 'front' }) => {
  const crack = {
    front: <path d="M 30 40 L 70 80 M 35 100 L 65 50 M 40 30 L 50 110" stroke="#FF6B1A" strokeWidth="0.6" opacity="0.7"/>,
    back:  <path d="M 25 90 L 75 110 M 40 30 L 60 130" stroke="#FF6B1A" strokeWidth="0.5" opacity="0.5"/>,
    close: <path d="M 20 70 L 80 80 M 30 50 L 70 100 M 45 20 L 55 120" stroke="#FF6B1A" strokeWidth="1" opacity="0.95"/>,
  }[tone];
  return (
    <button onClick={onClick} disabled={filled}
      style={{
        position: 'relative', aspectRatio: '3/4', borderRadius: 16,
        background: filled ? 'linear-gradient(135deg, #2a1810 0%, #0a0a0a 100%)' : '#0a0a0a',
        border: `1px dashed ${filled ? '#FF6B1A' : '#2c2c2e'}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: filled ? '#FF6B1A' : '#86868b', overflow: 'hidden',
        cursor: filled ? 'default' : 'pointer', padding: 0,
        transition: 'all 300ms cubic-bezier(0.25,0.1,0.25,1)',
      }}>
      {filled ? (
        <>
          <svg viewBox="0 0 100 140" style={{ width: '70%', height: '70%' }}>
            <rect x="25" y="10" width="50" height="120" rx="8" fill="#050505" stroke="#FF6B1A" strokeWidth="0.8"/>
            <rect x="40" y="14" width="20" height="4" rx="2" fill="#1a1a1a"/>
            {crack}
          </svg>
          <span style={{ position: 'absolute', bottom: 8, left: 10, fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: '#FF6B1A', letterSpacing: '0.1em' }}>0{idx} · {tone.toUpperCase()}</span>
        </>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/></svg>
          <span style={{ fontSize: 11, letterSpacing: '-0.011em' }}>{idx === 1 ? 'Front' : idx === 2 ? 'Back' : 'Close-up'}</span>
        </div>
      )}
    </button>
  );
};

// ------ intro / capture ------
const Intro = ({ onStart }) => {
  const [photos, setPhotos] = useState([]); // ['front','back','close']
  const slots = ['front','back','close'];
  const add = (i) => setPhotos(p => p.includes(slots[i]) ? p : [...p, slots[i]]);
  return (
    <>
      <Eyebrow>SNAP A QUOTE</Eyebrow>
      <h2 style={{ marginTop: 16, fontSize: 44, fontWeight: 600, letterSpacing: '-0.015em', lineHeight: 1.05 }}>
        Show us what<br/>we're dealing with.
      </h2>
      <p style={{ marginTop: 20, fontSize: 17, color: 'rgba(255,255,255,0.75)', letterSpacing: '-0.022em', lineHeight: 1.47, maxWidth: 520 }}>
        Snap or upload a photo — front, back, or the damage close-up. Three is best, one is fine.
      </p>
      <div style={{ marginTop: 40, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
        {[0,1,2].map(i => (
          <PhotoSlot key={i} idx={i+1} tone={slots[i]} filled={photos.includes(slots[i])} onClick={() => add(i)} />
        ))}
      </div>
      <div style={{ marginTop: 32, display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
        <button onClick={() => photos.length > 0 && onStart()}
          disabled={photos.length === 0}
          style={{
            height: 56, padding: '0 28px', background: '#FF6B1A', color: '#000', border: 0, borderRadius: 8,
            font: '500 18px Inter', letterSpacing: '-0.022em', cursor: photos.length ? 'pointer' : 'default',
            opacity: photos.length ? 1 : 0.35,
            transition: 'opacity 200ms',
          }}>Get my quote</button>
        <button style={{ background: 'transparent', border: 0, color: '#FFA366', fontSize: 14, cursor: 'pointer' }}>
          Not right? Pick it manually →
        </button>
      </div>
      <p style={{ marginTop: 36, fontSize: 12, color: '#86868b' }}>Final price confirmed after a free in-store diagnostic.</p>
    </>
  );
};

// ------ processing — cinematic scan animation ------
const Processing = ({ onDone }) => {
  const [phase, setPhase] = useState(0);
  // 0: scanning, 1: classifying, 2: fetching price — ~1.8s total
  useEffect(() => {
    const t1 = setTimeout(() => setPhase(1), 650);
    const t2 = setTimeout(() => setPhase(2), 1300);
    const t3 = setTimeout(() => onDone(), 1900);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, []);
  const LABELS = ['Scanning photos…', 'Identifying device…', 'Fetching starting price…'];
  return (
    <div style={{ padding: '60px 0', textAlign: 'center' }}>
      <div style={{ display: 'inline-block', position: 'relative', width: 220, height: 220 }}>
        <svg viewBox="0 0 220 220" width="220" height="220" style={{ position: 'absolute', inset: 0 }}>
          <defs>
            <linearGradient id="scanline" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#FF6B1A" stopOpacity="0"/>
              <stop offset="50%" stopColor="#FF6B1A" stopOpacity="0.9"/>
              <stop offset="100%" stopColor="#FF6B1A" stopOpacity="0"/>
            </linearGradient>
          </defs>
          {/* phone silhouette */}
          <rect x="75" y="30" width="70" height="160" rx="14" fill="#0a0a0a" stroke="#2c2c2e" strokeWidth="1"/>
          <rect x="82" y="38" width="56" height="144" rx="8" fill="#050505"/>
          <rect x="100" y="42" width="20" height="3" rx="1.5" fill="#1a1a1a"/>
          {/* cracks */}
          <path d="M 90 90 L 130 120 M 95 50 L 125 180 M 85 150 L 135 170" stroke="#FF6B1A" strokeWidth="0.6" opacity="0.6"/>
          {/* scan line */}
          <rect x="75" y="30" width="70" height="30" fill="url(#scanline)" style={{ animation: 'scan 1.4s ease-in-out infinite' }}/>
          {/* corner brackets */}
          {[[60,20],[160,20],[60,200],[160,200]].map(([x,y],i) => (
            <g key={i} stroke="#FF6B1A" strokeWidth="1.5" fill="none" opacity="0.8">
              <path d={i===0?`M ${x} ${y+12} L ${x} ${y} L ${x+12} ${y}`:
                        i===1?`M ${x-12} ${y} L ${x} ${y} L ${x} ${y+12}`:
                        i===2?`M ${x} ${y-12} L ${x} ${y} L ${x+12} ${y}`:
                              `M ${x-12} ${y} L ${x} ${y} L ${x} ${y-12}`}/>
            </g>
          ))}
        </svg>
      </div>
      <h2 style={{ marginTop: 36, fontSize: 28, fontWeight: 600, letterSpacing: '-0.015em' }}>Taking a look…</h2>
      <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'center' }}>
        {LABELS.map((l, i) => (
          <div key={i} style={{
            fontSize: 13, color: i < phase ? '#86868b' : i === phase ? '#FF6B1A' : '#3a3a3c',
            display: 'flex', alignItems: 'center', gap: 8,
            transition: 'color 300ms',
          }}>
            <svg width="12" height="12" viewBox="0 0 12 12">
              {i < phase ? <path d="M 2 6 L 5 9 L 10 3" stroke="#86868b" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/> :
               i === phase ? <circle cx="6" cy="6" r="3" fill="#FF6B1A"><animate attributeName="r" values="3;4.5;3" dur="0.9s" repeatCount="indefinite"/></circle> :
               <circle cx="6" cy="6" r="2" fill="#3a3a3c"/>}
            </svg>
            {l}
          </div>
        ))}
      </div>
    </div>
  );
};

// ------ result — morph-in device name ------
const Result = ({ onBook, onBack }) => {
  const target = 'iPhone 13';
  const [device, setDevice] = useState('');
  useEffect(() => {
    let i = 0;
    const id = setInterval(() => {
      i++;
      setDevice(target.slice(0, i));
      if (i >= target.length) clearInterval(id);
    }, 55);
    return () => clearInterval(id);
  }, []);
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <Eyebrow>CONFIDENCE 94%</Eyebrow>
        <span style={{ width: 4, height: 4, borderRadius: '50%', background: '#86868b' }} />
        <span style={{ fontSize: 11, letterSpacing: '0.2em', color: '#86868b' }}>IDENTIFIED</span>
      </div>
      <h2 style={{ marginTop: 16, fontSize: 44, fontWeight: 600, letterSpacing: '-0.015em', lineHeight: 1.08 }}>
        Looks like an<br/>
        <span style={{
          color: '#FF6B1A',
          fontVariationSettings: `"wght" ${500 + device.length * 15}`,
          transition: 'font-variation-settings 120ms',
        }}>{device}<span style={{ opacity: device.length < target.length ? 1 : 0, color: '#FF6B1A' }}>▌</span></span><br/>
        with a <u style={{ textDecorationColor: '#FF6B1A', textDecorationThickness: 2, textUnderlineOffset: 6 }}>cracked screen</u>.
      </h2>
      <div style={{ marginTop: 40, padding: 28, background: '#000', border: '1px solid #2c2c2e', borderRadius: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 16, flexWrap: 'wrap' }}>
          <div>
            <Eyebrow>STARTING FROM</Eyebrow>
            <div style={{ marginTop: 8, display: 'flex', alignItems: 'baseline', gap: 2 }}>
              <span style={{ fontSize: 38, fontWeight: 500, color: '#86868b' }}>£</span>
              <span style={{ fontSize: 72, fontWeight: 600, letterSpacing: '-0.025em', lineHeight: 1 }}>89</span>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <Eyebrow>TURNAROUND</Eyebrow>
            <div style={{ marginTop: 8, fontSize: 22, fontWeight: 500, letterSpacing: '-0.011em' }}>Same day</div>
            <div style={{ marginTop: 2, fontSize: 12, color: '#86868b' }}>Usually under an hour</div>
          </div>
        </div>
        <div style={{ marginTop: 28, paddingTop: 24, borderTop: '1px solid #1a1a1a', display: 'flex', flexDirection: 'column', gap: 16 }}>
          <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8, fontSize: 13, color: '#86868b' }}>
            {['Genuine-quality OLED replacement', 'True Tone calibrated', '12-month warranty on parts & labour'].map(x => (
              <li key={x} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <svg width="12" height="12" viewBox="0 0 12 12"><path d="M 2 6 L 5 9 L 10 3" stroke="#FF6B1A" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                {x}
              </li>
            ))}
          </ul>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <button onClick={onBook} style={{ height: 56, padding: '0 28px', background: '#FF6B1A', color: '#000', border: 0, borderRadius: 8, font: '500 17px Inter', letterSpacing: '-0.022em', cursor: 'pointer', flex: '1 1 200px' }}>Book this repair</button>
            <button style={{ height: 56, padding: '0 24px', background: 'transparent', color: '#fff', border: 0, borderRadius: 8, boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.2)', font: '500 17px Inter', cursor: 'pointer' }}>Call the shop</button>
          </div>
        </div>
      </div>
      <div style={{ marginTop: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
        <p style={{ margin: 0, fontSize: 12, color: '#86868b' }}>Final price confirmed after a free in-store diagnostic.</p>
        <button onClick={onBack} style={{ background: 'transparent', border: 0, color: '#FFA366', fontSize: 13, cursor: 'pointer' }}>Not right? Retake →</button>
      </div>
    </>
  );
};

// ------ confirm ------
const Confirm = ({ onReset }) => (
  <div style={{ textAlign: 'center', padding: '40px 0' }}>
    <div style={{ width: 72, height: 72, borderRadius: '50%', background: '#FF6B1A', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
      <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#000" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12 L10 18 L20 6"/></svg>
    </div>
    <h2 style={{ marginTop: 28, fontSize: 36, fontWeight: 600, letterSpacing: '-0.015em' }}>Got it.</h2>
    <p style={{ marginTop: 12, fontSize: 16, color: '#86868b', maxWidth: 360, margin: '12px auto 0', lineHeight: 1.5 }}>
      We'll be in touch within the hour during shop hours. Your reference:
    </p>
    <div style={{ marginTop: 16, padding: '12px 20px', display: 'inline-block', background: '#0a0a0a', border: '1px solid #FFA366', borderRadius: 10, fontFamily: 'JetBrains Mono, monospace', fontSize: 15, color: '#fff' }}>
      FS-20260419-R7M4
    </div>
    <div style={{ marginTop: 32, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
      <button style={{ height: 48, padding: '0 24px', background: 'transparent', color: '#fff', border: 0, borderRadius: 8, boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.2)', font: '500 16px Inter', cursor: 'pointer' }}>Track repair status</button>
      <button onClick={onReset} style={{ height: 48, padding: '0 24px', background: '#FF6B1A', color: '#000', border: 0, borderRadius: 8, font: '500 16px Inter', cursor: 'pointer' }}>Book another</button>
    </div>
    <div style={{ marginTop: 20 }}>
      <a href="../marketing/" style={{ color: '#FFA366', fontSize: 13, textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
        Back to the site
      </a>
    </div>
  </div>
);

// ------ sheet wrapper ------
const CameraQuote = () => {
  const [step, setStep] = useState('intro'); // intro | processing | result | confirm
  const reset = () => setStep('intro');
  const closeOrBack = () => {
    // If we're mid-flow, reset to intro. If we're on intro already, navigate
    // back to the marketing site — that's what "close" means in standalone mode.
    if (step === 'intro') { window.location.href = '../marketing/'; }
    else { reset(); }
  };
  return (
    <div style={{ position: 'relative', width: '100%', maxWidth: 720, margin: '0 auto', background: '#0a0a0a', borderRadius: 24, overflow: 'hidden', border: '1px solid #2c2c2e', boxShadow: '0 48px 120px rgba(0,0,0,0.6), inset 0 1px 0 rgba(255,255,255,0.06)' }}>
      {/* handle */}
      <div style={{ padding: '14px 0 0', textAlign: 'center' }}>
        <div style={{ width: 40, height: 4, background: '#2c2c2e', borderRadius: 2, margin: '0 auto' }} />
      </div>
      {/* header bar */}
      <div style={{ padding: '16px 32px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: '1px solid #1a1a1a' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 20, height: 20, background: '#FF6B1A', borderRadius: '50%' }} />
          <span style={{ fontSize: 13, color: '#86868b', letterSpacing: '-0.011em' }}>The Fone Shop</span>
        </div>
        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          {['intro','processing','result','confirm'].map(s => (
            <span key={s} style={{
              width: step === s ? 20 : 6, height: 6, borderRadius: 3,
              background: ['intro','processing','result','confirm'].indexOf(step) >= ['intro','processing','result','confirm'].indexOf(s) ? '#FF6B1A' : '#2c2c2e',
              transition: 'all 400ms cubic-bezier(0.25,0.1,0.25,1)',
            }}/>
          ))}
        </div>
        <button
          onClick={closeOrBack}
          aria-label={step === 'intro' ? 'Back to the site' : 'Start over'}
          title={step === 'intro' ? 'Back to the site' : 'Start over'}
          style={{ background: 'transparent', border: 0, color: '#fff', fontSize: 22, cursor: 'pointer', width: 32, height: 32 }}>×</button>
      </div>
      {/* body */}
      <div style={{ padding: '40px 32px 48px', minHeight: 540 }}>
        {step === 'intro' && <Intro onStart={() => setStep('processing')} />}
        {step === 'processing' && <Processing onDone={() => setStep('result')} />}
        {step === 'result' && <Result onBook={() => setStep('confirm')} onBack={reset} />}
        {step === 'confirm' && <Confirm onReset={reset} />}
      </div>
    </div>
  );
};

// reset control (debug only — cycles the demo)
const DemoBar = ({ onReset }) => (
  <div style={{ position: 'fixed', top: 20, left: '50%', transform: 'translateX(-50%)', zIndex: 10, padding: '8px 16px', background: 'rgba(10,10,10,0.8)', backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)', borderRadius: 980, border: '1px solid #2c2c2e', fontSize: 12, color: '#86868b', letterSpacing: '-0.011em', display: 'flex', alignItems: 'center', gap: 12 }}>
    <span>Camera Quote · live demo</span>
    <button onClick={onReset} style={{ background: 'transparent', border: 0, color: '#FFA366', cursor: 'pointer', fontSize: 12 }}>Restart →</button>
  </div>
);

Object.assign(window, { CameraQuote, DemoBar });
