const { useState, useEffect, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentColor": "#FEC20E",
  "showBanner": true,
  "heroSize": "full"
}/*EDITMODE-END*/;

/* ── Device Data ─────────────────────────────────────────────────────────── */
const DEVICES = [
  { name:'iPhone 17 Pro Max', brand:'Apple', type:'phone', prices:[1250,820,390] },
  { name:'iPhone 17 Pro',     brand:'Apple', type:'phone', prices:[1050,700,330] },
  { name:'iPhone 17',         brand:'Apple', type:'phone', prices:[880,580,270]  },
  { name:'iPhone 16 Pro Max', brand:'Apple', type:'phone', prices:[980,660,310]  },
  { name:'iPhone 16 Pro',     brand:'Apple', type:'phone', prices:[820,540,250]  },
  { name:'iPhone 16',         brand:'Apple', type:'phone', prices:[680,440,200]  },
  { name:'iPhone 15 Pro Max', brand:'Apple', type:'phone', prices:[720,480,220]  },
  { name:'iPhone 15 Pro',     brand:'Apple', type:'phone', prices:[580,380,170]  },
  { name:'iPhone 15',         brand:'Apple', type:'phone', prices:[460,300,135]  },
  { name:'iPhone 14 Pro Max', brand:'Apple', type:'phone', prices:[560,360,160]  },
  { name:'iPhone 14',         brand:'Apple', type:'phone', prices:[340,220,95]   },
  { name:'iPhone 13',         brand:'Apple', type:'phone', prices:[260,165,72]   },
  { name:'iPhone 12',         brand:'Apple', type:'phone', prices:[180,115,50]   },
  { name:'Galaxy S25 Ultra',  brand:'Samsung', type:'phone', prices:[1050,700,330] },
  { name:'Galaxy S25+',       brand:'Samsung', type:'phone', prices:[840,560,260]  },
  { name:'Galaxy S25',        brand:'Samsung', type:'phone', prices:[680,450,210]  },
  { name:'Galaxy S24 Ultra',  brand:'Samsung', type:'phone', prices:[880,580,270]  },
  { name:'Galaxy Z Fold 6',   brand:'Samsung', type:'phone', prices:[1100,720,340] },
  { name:'Galaxy Z Flip 6',   brand:'Samsung', type:'phone', prices:[640,420,195]  },
  { name:'Pixel 9 Pro XL',    brand:'Google',  type:'phone', prices:[780,520,245]  },
  { name:'Pixel 9 Pro',       brand:'Google',  type:'phone', prices:[680,450,210]  },
  { name:'Pixel 9',           brand:'Google',  type:'phone', prices:[520,345,160]  },
  { name:'iPad Pro 13" M4',   brand:'Apple',   type:'tablet', prices:[1250,840,400] },
  { name:'iPad Pro 11" M4',   brand:'Apple',   type:'tablet', prices:[980,660,310]  },
  { name:'iPad Air M2',       brand:'Apple',   type:'tablet', prices:[680,450,210]  },
  { name:'iPad Mini 7',       brand:'Apple',   type:'tablet', prices:[480,320,148]  },
  { name:'Galaxy Tab S10 Ultra', brand:'Samsung', type:'tablet', prices:[780,520,245] },
  { name:'MacBook Pro 16" M4',brand:'Apple',   type:'laptop', prices:[2200,1580,900] },
  { name:'MacBook Pro 14" M4',brand:'Apple',   type:'laptop', prices:[1900,1360,780] },
  { name:'MacBook Air 15" M3',brand:'Apple',   type:'laptop', prices:[1380,960,550]  },
  { name:'MacBook Air 13" M3',brand:'Apple',   type:'laptop', prices:[1160,820,470]  },
  { name:'Apple Watch Ultra 2',brand:'Apple',  type:'watch', prices:[580,390,180]   },
  { name:'Apple Watch Series 10',brand:'Apple',type:'watch', prices:[380,255,118]   },
  { name:'Galaxy Watch 7',    brand:'Samsung', type:'watch', prices:[280,188,86]    },
];

/* ── Hooks ───────────────────────────────────────────────────────────────── */
function useTypewriter(words, speed = 85, pause = 2400) {
  const [display, setDisplay] = useState(words[0]);
  const [wi, setWi] = useState(0);
  const [ci, setCi] = useState(words[0].length);
  const [del, setDel] = useState(false);

  useEffect(() => {
    const word = words[wi];
    if (!del && ci < word.length) {
      const t = setTimeout(() => { setDisplay(word.slice(0, ci+1)); setCi(c=>c+1); }, speed);
      return () => clearTimeout(t);
    }
    if (!del && ci === word.length) {
      const t = setTimeout(() => setDel(true), pause);
      return () => clearTimeout(t);
    }
    if (del && ci > 0) {
      const t = setTimeout(() => { setDisplay(word.slice(0, ci-1)); setCi(c=>c-1); }, speed/2);
      return () => clearTimeout(t);
    }
    if (del && ci === 0) {
      setDel(false);
      setWi(i => (i+1) % words.length);
    }
  }, [ci, del, wi, words, speed, pause]);

  return display;
}

function useScrollReveal() {
  useEffect(() => {
    const obs = new IntersectionObserver(entries => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('visible'); obs.unobserve(e.target); } });
    }, { threshold: 0.12 });
    document.querySelectorAll('.reveal, .reveal-left, .reveal-right').forEach(el => obs.observe(el));
    return () => obs.disconnect();
  }, []);
}

function useCountUp(target, active, duration = 1800) {
  const [val, setVal] = useState(0);
  useEffect(() => {
    if (!active) return;
    let start; const step = t => {
      if (!start) start = t;
      const p = Math.min((t-start)/duration, 1);
      setVal(Math.floor(p * target));
      if (p < 1) requestAnimationFrame(step);
    };
    requestAnimationFrame(step);
  }, [active, target, duration]);
  return val;
}

/* ── Fault list ─────────────────────────────────────────────────────────── */
const FAULTS = [
  { id:'battery',       label:'Battery Health Fault',          deduct:.05 },
  { id:'cosmetic',      label:'Excessive Dents / Scratches',    deduct:.07 },
  { id:'backGlass',     label:'Cracked Back Glass',             deduct:.06 },
  { id:'frontGlass',    label:'Cracked Front Display',          deduct:.14 },
  { id:'charging',      label:'Damaged Charging Port',          deduct:.06 },
  { id:'frame',         label:'Damaged Frame',                  deduct:.05 },
  { id:'earReceiver',   label:'Faulty Ear Receiver',            deduct:.04 },
  { id:'faceId',        label:'Faulty Face ID / Front Camera',  deduct:.08 },
  { id:'microphone',    label:'Faulty Microphone',              deduct:.04 },
  { id:'powerBtn',      label:'Faulty Power Button',            deduct:.05 },
  { id:'rearCamera',    label:'Faulty Rear Camera / Lens',      deduct:.07 },
  { id:'speaker',       label:'Faulty Speaker',                 deduct:.04 },
  { id:'vibration',     label:'Faulty Vibration',               deduct:.03 },
  { id:'volumeBtn',     label:'Faulty Volume Buttons',          deduct:.03 },
  { id:'simTray',       label:'Missing SIM Tray',               deduct:.02 },
  { id:'reception',     label:'Reception Issues',               deduct:.05 },
  { id:'software',      label:'Software Issue',                 deduct:.04 },
];

/* ── Quote Card (hero right col) ────────────────────────────────────────── */
const TYPE_FILTERS = [
  { key:'all',    label:'All' },
  { key:'phone',  label:'Phone' },
  { key:'tablet', label:'Tablet' },
  { key:'laptop', label:'Laptop' },
  { key:'watch',  label:'Watch' },
];

const TYPE_ICONS = {
  phone:  <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><rect x="2.5" y=".5" width="8" height="12" rx="1.5" stroke="currentColor" strokeWidth="1.3"/><circle cx="6.5" cy="10" r=".8" fill="currentColor"/></svg>,
  tablet: <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><rect x="1" y="1" width="11" height="11" rx="1.5" stroke="currentColor" strokeWidth="1.3"/><circle cx="6.5" cy="9.5" r=".7" fill="currentColor"/></svg>,
  laptop: <svg width="14" height="13" viewBox="0 0 14 13" fill="none"><rect x="1" y="1.5" width="12" height="8" rx="1" stroke="currentColor" strokeWidth="1.3"/><path d="M0 11h14" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>,
  watch:  <svg width="12" height="14" viewBox="0 0 12 14" fill="none"><circle cx="6" cy="7" r="4" stroke="currentColor" strokeWidth="1.3"/><rect x="4" y=".5" width="4" height="2.5" rx=".8" stroke="currentColor" strokeWidth="1.1"/><rect x="4" y="11" width="4" height="2.5" rx=".8" stroke="currentColor" strokeWidth="1.1"/></svg>,
};

function QuoteCard() {
  const [step, setStep]       = useState(1);
  const [query, setQuery]     = useState('');
  const [typeFilter, setType] = useState('all');
  const [results, setRes]     = useState([]);
  const [open, setOpen]       = useState(false);
  const [device, setDevice]   = useState(null);
  const [cond, setCond]       = useState('');
  const [faults, setFaults]   = useState(new Set());
  const ref = useRef();
  const inputRef = useRef();

  useEffect(() => {
    const q = query.toLowerCase();
    const filtered = DEVICES.filter(d => {
      const matchType  = typeFilter === 'all' || d.type === typeFilter;
      const matchQuery = q.length < 2 || `${d.brand} ${d.name}`.toLowerCase().includes(q);
      return matchType && matchQuery;
    });
    if (q.length > 1 || (q.length === 0 && typeFilter !== 'all')) {
      setRes(filtered.slice(0, 6));
      setOpen(filtered.length > 0);
    } else {
      setRes([]);
      setOpen(false);
    }
  }, [query, typeFilter]);

  useEffect(() => {
    const fn = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', fn);
    return () => document.removeEventListener('mousedown', fn);
  }, []);

  const toggleFault = id => {
    setFaults(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  const pick = d => { setDevice(d); setQuery(`${d.brand} ${d.name}`); setOpen(false); setStep(2); };
  const reset = () => { setStep(1); setQuery(''); setDevice(null); setCond(''); setType('all'); setFaults(new Set()); };

  /* live price: base - fault deductions, floored at Dead price */
  const baseWorkingPrice = device ? device.prices[1] : 0;
  const faultDeduction = device && cond === 'Working'
    ? [...faults].reduce((sum, id) => {
        const f = FAULTS.find(x => x.id === id);
        return sum + (f ? Math.round(baseWorkingPrice * f.deduct) : 0);
      }, 0)
    : 0;
  const price = device && cond
    ? cond === 'As New' ? device.prices[0]
    : cond === 'Dead'   ? device.prices[2]
    : Math.max(baseWorkingPrice - faultDeduction, device.prices[2])
    : null;

  const handleTypeClick = key => { setType(key); inputRef.current && inputRef.current.focus(); };

  const POPULAR = [
    { name:'iPhone 17 Pro Max', brand:'Apple',   type:'phone',  prices:[1250,820,390]  },
    { name:'Galaxy S25 Ultra',  brand:'Samsung', type:'phone',  prices:[1050,700,330]  },
    { name:'MacBook Air 13" M3',brand:'Apple',   type:'laptop', prices:[1160,820,470]  },
  ];

  const suggestions = typeFilter !== 'all' && query.length === 0
    ? DEVICES.filter(d => d.type === typeFilter).slice(0, 3)
    : [];

  /* progress dots: step1=device, step2=condition, step3=faults(Working), step4=quote */
  const totalSteps = 3;
  const progressStep = step === 1 ? 1 : step === 2 ? 2 : step === 3 ? 3 : 3;

  const ProgressBar = () => (
    <div style={{ display:'flex', gap:'6px', marginBottom:'18px', alignItems:'center' }}>
      {['Device','Condition','Quote'].map((label, i) => {
        const active = progressStep > i;
        const current = progressStep === i + 1;
        return (
          <React.Fragment key={label}>
            <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:'4px' }}>
              <div style={{
                width:'24px', height:'24px', borderRadius:'50%',
                background: active ? 'var(--navy)' : 'var(--border)',
                color: active ? 'white' : 'var(--tert)',
                fontSize:'11px', fontWeight:700,
                display:'flex', alignItems:'center', justifyContent:'center',
                transition:'all .2s',
                boxShadow: current ? '0 0 0 3px rgba(38,61,137,.15)' : 'none',
              }}>{active && !current ? <svg width="11" height="9" viewBox="0 0 11 9" fill="none"><path d="M1 4l3.5 3.5L10 1" stroke="#263D89" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg> : i+1}</div>
              <span style={{ fontSize:'10px', fontWeight:600, color: active ? 'var(--navy)' : 'var(--tert)', whiteSpace:'nowrap' }}>{label}</span>
            </div>
            {i < 2 && <div style={{ flex:1, height:'2px', background: progressStep > i+1 ? 'var(--navy)' : 'var(--border)', borderRadius:'2px', marginBottom:'14px', transition:'background .3s' }}></div>}
          </React.Fragment>
        );
      })}
    </div>
  );

  return (
    <div className="qcard">
      <div className="qcard-title">Get Your Instant Quote</div>
      <div className="qcard-sub">60 seconds &bull; No obligation</div>
      {step > 1 && <ProgressBar />}

      {/* ── Step 1: Search ── */}
      {step === 1 && (
        <>
          <div style={{ display:'flex', gap:'5px', marginBottom:'10px' }}>
            {TYPE_FILTERS.map(f => (
              <button key={f.key} onClick={() => handleTypeClick(f.key)} style={{
                flex: f.key === 'all' ? '0 0 auto' : 1,
                padding:'6px 0',
                border:'1.5px solid ' + (typeFilter === f.key ? 'var(--navy)' : 'var(--border)'),
                borderRadius:'var(--r-md)',
                background: typeFilter === f.key ? 'var(--navy)' : 'var(--white)',
                color: typeFilter === f.key ? 'var(--white)' : 'var(--primary)',
                fontSize:'11.5px', fontWeight:600, fontFamily:'var(--font)', cursor:'pointer',
                transition:'all .15s', display:'flex', flexDirection:'column', alignItems:'center', gap:'3px',
                paddingLeft: f.key === 'all' ? '12px' : '0',
                paddingRight: f.key === 'all' ? '12px' : '0',
              }}>
                {f.key !== 'all' && <span style={{ color: typeFilter === f.key ? 'rgba(255,255,255,.7)' : 'var(--tert)', display:'flex' }}>{TYPE_ICONS[f.key]}</span>}
                {f.label}
              </button>
            ))}
          </div>

          <div className="qcard-search-wrap" ref={ref}>
            <div className="qcard-search">
              <svg width="15" height="15" viewBox="0 0 15 15" fill="none" style={{ flexShrink:0 }}>
                <circle cx="6.5" cy="6.5" r="5" stroke="#768b9e" strokeWidth="1.5"/>
                <path d="M10.5 10.5l3 3" stroke="#768b9e" strokeWidth="1.5" strokeLinecap="round"/>
              </svg>
              <input ref={inputRef} className="qcard-input"
                placeholder={typeFilter === 'all' ? 'iPhone 17, Galaxy S25, MacBook…' : `Search ${typeFilter}s…`}
                value={query} onChange={e => setQuery(e.target.value)}
                onFocus={() => { if (results.length) setOpen(true); }} />
              {query && <button onClick={() => { setQuery(''); setRes([]); setOpen(false); }} style={{ color:'var(--tert)', fontSize:'14px', lineHeight:1, background:'none', border:'none', cursor:'pointer' }}>✕</button>}
            </div>
            {suggestions.length > 0 && !open && (
              <div style={{ display:'flex', flexWrap:'wrap', gap:'5px', marginTop:'8px' }}>
                {suggestions.map(d => (
                  <button key={d.name} onClick={() => pick(d)} style={{
                    padding:'4px 10px', border:'1px solid var(--border)', borderRadius:'var(--r-xl)',
                    background:'var(--white)', fontSize:'12px', fontWeight:600, color:'var(--navy)',
                    fontFamily:'var(--font)', cursor:'pointer', transition:'all .15s', display:'flex', alignItems:'center', gap:'5px',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.borderColor='var(--navy)'; e.currentTarget.style.background='var(--light)'; }}
                  onMouseLeave={e => { e.currentTarget.style.borderColor='var(--border)'; e.currentTarget.style.background='var(--white)'; }}>
                    {d.brand} {d.name}
                    <span style={{ color:'var(--blue)', fontWeight:700 }}>${d.prices[0].toLocaleString()}</span>
                  </button>
                ))}
              </div>
            )}
            {open && results.length > 0 && (
              <div className="qcard-dropdown">
                {results.map(d => (
                  <div key={d.name} className="qcard-result" onClick={() => pick(d)}>
                    <div>
                      <div style={{ fontSize:'13.5px', fontWeight:700, color:'var(--navy)' }}>{d.brand} {d.name}</div>
                      <div style={{ fontSize:'11.5px', color:'var(--muted)', marginTop:'1px' }}>{d.type.charAt(0).toUpperCase()+d.type.slice(1)}</div>
                    </div>
                    <div style={{ fontSize:'13px', fontWeight:700, color:'var(--blue)', whiteSpace:'nowrap' }}>Up to ${d.prices[0].toLocaleString()}</div>
                  </div>
                ))}
              </div>
            )}
          </div>

          <div className="qcard-pop-label" style={{ marginTop:'14px' }}>Popular right now</div>
          <div className="qcard-popular">
            {POPULAR.map(d => (
              <button key={d.name} className="qcard-pop-item" onClick={() => pick(d)}>
                <span className="qcard-pop-name">{d.brand} {d.name}</span>
                <span className="qcard-pop-price">Up to ${d.prices[0].toLocaleString()}</span>
              </button>
            ))}
          </div>
          <a href="Sell Your Phone.html" className="qcard-browse">Browse all models →</a>
        </>
      )}

      {/* ── Step 2: Condition ── */}
      {step === 2 && (
        <>
          <div className="qcard-selected">
            <div>
              <div className="qcard-sel-label">Your device</div>
              <div className="qcard-sel-name">{device.brand} {device.name}</div>
            </div>
            <button className="qcard-change" onClick={reset}>Change</button>
          </div>
          <div className="qcard-cond-label">Select condition</div>
          <div className="qcard-conds">
            {[['As New',0,'No scratches, perfect'],['Working',1,'Minor wear, fully functional'],['Dead',2,'Broken or won\'t power on']].map(([c,idx,hint]) => (
              <button key={c} className={'qcard-cond'+(cond===c?' active':'')}
                onClick={() => {
                  setCond(c);
                  setFaults(new Set());
                  setStep(c === 'Working' ? 3 : 4);
                }}>
                <span className="qcard-cond-name">{c}</span>
                <span className="qcard-cond-price">${device.prices[idx].toLocaleString()}</span>
                <span className="qcard-cond-hint">{hint}</span>
              </button>
            ))}
          </div>
        </>
      )}

      {/* ── Step 3: Fault selection (Working only) ── */}
      {step === 3 && (
        <>
          <div className="qcard-selected" style={{ marginBottom:'14px' }}>
            <div>
              <div className="qcard-sel-label">{device.brand} {device.name} &bull; Working</div>
              <div className="qcard-sel-name" style={{ fontSize:'13px' }}>Any faults with this device?</div>
            </div>
            <button className="qcard-change" onClick={() => { setCond(''); setStep(2); }}>Back</button>
          </div>

          {/* Live price preview */}
          <div style={{
            display:'flex', justifyContent:'space-between', alignItems:'center',
            background:'var(--light)', borderRadius:'var(--r-md)', padding:'10px 14px', marginBottom:'12px',
          }}>
            <div style={{ fontSize:'12px', color:'var(--muted)', fontWeight:600 }}>
              {faults.size === 0 ? 'No faults selected' : `${faults.size} fault${faults.size > 1 ? 's' : ''} selected`}
            </div>
            <div style={{ textAlign:'right' }}>
              <div style={{ fontSize:'10px', color:'var(--muted)', fontWeight:600, textTransform:'uppercase', letterSpacing:'.06em' }}>Your quote</div>
              <div style={{ fontSize:'22px', fontWeight:900, color:'var(--navy)', letterSpacing:'-.03em', lineHeight:1.1 }}>
                ${Math.max(baseWorkingPrice - faultDeduction, device.prices[2]).toLocaleString()}
              </div>
            </div>
          </div>

          {/* Fault checkboxes */}
          <div style={{ maxHeight:'210px', overflowY:'auto', marginBottom:'12px',
            scrollbarWidth:'thin', scrollbarColor:'var(--border) transparent' }}>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'6px' }}>
              {FAULTS.map(f => {
                const checked = faults.has(f.id);
                return (
                  <button key={f.id} onClick={() => toggleFault(f.id)} style={{
                    display:'flex', alignItems:'flex-start', gap:'7px', padding:'8px 10px',
                    border:'1.5px solid ' + (checked ? 'var(--navy)' : 'var(--border)'),
                    borderRadius:'var(--r-md)', background: checked ? 'rgba(38,61,137,.05)' : 'var(--white)',
                    cursor:'pointer', textAlign:'left', fontFamily:'var(--font)', transition:'all .15s',
                  }}>
                    <div style={{
                      width:'15px', height:'15px', borderRadius:'4px', flexShrink:0, marginTop:'1px',
                      border:'1.5px solid ' + (checked ? 'var(--navy)' : 'var(--border)'),
                      background: checked ? 'var(--navy)' : 'var(--white)',
                      display:'flex', alignItems:'center', justifyContent:'center', transition:'all .15s',
                    }}>
                      {checked && <svg width="9" height="7" viewBox="0 0 9 7" fill="none"><path d="M1 3.5l2.5 2.5L8 1" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                    </div>
                    <div style={{ fontSize:'11px', fontWeight:600, color:'var(--navy)', lineHeight:1.35 }}>{f.label}</div>
                  </button>
                );
              })}
            </div>
          </div>
          <div style={{ fontSize:'11px', color:'var(--tert)', marginBottom:'12px', lineHeight:1.5 }}>
            * Tick all faults that apply. Price adjusts automatically.
          </div>
          <button className="qcard-btn" style={{ display:'block', width:'100%', textDecoration:'none', textAlign:'center', cursor:'pointer' }}
            onClick={() => setStep(4)}>
            See My Final Quote →
          </button>
          <button className="qcard-back" onClick={() => { setCond(''); setStep(2); }}>← Change condition</button>
        </>
      )}

      {/* ── Step 4: Price + Accept ── */}
      {step === 4 && (
        <>
          <div className="qcard-selected">
            <div>
              <div className="qcard-sel-label">{device.brand} {device.name} &bull; {cond}{faults.size > 0 ? ` (+${faults.size} fault${faults.size>1?'s':''})` : ''}</div>
              <div className="qcard-sel-name" style={{ fontSize:'13px', fontWeight:600 }}>Estimated trade-in value</div>
            </div>
            <button className="qcard-change" onClick={reset}>Start over</button>
          </div>
          <div className="qcard-price-wrap">
            <div className="qcard-price">${price.toLocaleString()}</div>
            <div className="qcard-price-note">Final price confirmed after inspection<br />Paid within 3–5 business days</div>
          </div>
          <a href={(() => {
            const p = new URLSearchParams();
            p.set('type', device.type);
            p.set('brand', device.brand);
            p.set('model', device.name);
            p.set('condition', cond);
            p.set('quote', price);
            if (faults.size > 0) p.set('faults', [...faults].join(','));
            return `Sell Your Phone.html?${p.toString()}`;
          })()} className="qcard-btn">Accept &amp; Sell Now →</a>
          <button className="qcard-back" onClick={() => {
            if (cond === 'Working') { setStep(3); } else { setCond(''); setStep(2); }
          }}>← {cond === 'Working' ? 'Edit faults' : 'Change condition'}</button>
        </>
      )}
    </div>
  );
}

/* ── Hero ───────────────────────────────────────────────────────────────── */
function Hero({ heroSize }) {
  const typed = useTypewriter(['Instant Cash','Top Dollar','Fast Payment','Real Value']);
  return (
    <section className="hero" id="sell" style={heroSize==='compact'?{padding:'52px 32px 64px'}:{}}>
      <div className="blob blob-1"></div>
      <div className="blob blob-2"></div>
      <div className="blob blob-3"></div>
      <div className="hero-inner">

        {/* LEFT — headline + stats */}
        <div style={{ position:'relative', zIndex:1 }}>
          <div className="hero-tag">Australia's #1 Tech Buyback</div>
          <h1 className="hero-h1">
            Sell Your Devices<br/>For <em>{typed}<span className="type-cursor"></span></em>
          </h1>
          <p style={{ fontSize:'16px', color:'rgba(255,255,255,.55)', lineHeight:1.7, marginBottom:'24px', maxWidth:'440px' }}>
            Skip the dodgy marketplace. Free shipping, fair offers, and payment in 3–5 business days.
          </p>

          {/* Trust badges row */}
          <div style={{ display:'flex', flexWrap:'wrap', gap:'10px', marginBottom:'32px' }}>
            {[
              [<svg key="s" width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M12 2L3 7v6c0 5.25 3.75 10.15 9 11.35C17.25 23.15 21 18.25 21 13V7L12 2z" stroke="rgba(255,255,255,.9)" strokeWidth="2" strokeLinejoin="round"/></svg>,'Price Beat +5%'],
              [<svg key="t" width="13" height="13" viewBox="0 0 24 24" fill="none"><rect x="1" y="10" width="15" height="8" rx="1" stroke="rgba(255,255,255,.9)" strokeWidth="2"/><path d="M16 13h4l3 4H16v-4z" stroke="rgba(255,255,255,.9)" strokeWidth="2" strokeLinejoin="round"/><circle cx="5.5" cy="18.5" r="1.5" fill="rgba(255,255,255,.9)"/><circle cx="18.5" cy="18.5" r="1.5" fill="rgba(255,255,255,.9)"/></svg>,'Free Shipping'],
              [<svg key="b" width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="rgba(255,255,255,.9)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>,'Paid in 3–5 days'],
              [<svg key="r" width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" stroke="rgba(255,255,255,.9)" strokeWidth="2" strokeLinecap="round"/><path d="M3 3v5h5" stroke="rgba(255,255,255,.9)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>,'Risk-Free Returns'],
            ].map(([ic,t]) => (
              <div key={t} style={{
                display:'inline-flex', alignItems:'center', gap:'7px',
                background:'rgba(255,255,255,.08)', border:'1px solid rgba(255,255,255,.12)',
                padding:'6px 12px', borderRadius:'999px',
                fontSize:'12px', fontWeight:600, color:'rgba(255,255,255,.85)',
                backdropFilter:'blur(6px)',
              }}>
                {ic}{t}
              </div>
            ))}
          </div>

          <div className="hero-stats">
            {[['$422M+','Paid to Aussies'],['50K+','Devices bought'],['4.9/5','Google'],['10+','Years']].map(([n,l]) => (
              <div key={l} className="hero-stat">
                <span className="hero-stat-num">{n}</span>
                <span className="hero-stat-label">{l}</span>
              </div>
            ))}
          </div>
        </div>

        {/* RIGHT — quote card */}
        <div style={{ position:'relative', zIndex:1 }}>
          <QuoteCard />
        </div>
      </div>
    </section>
  );
}
function AnnBar({ show }) {
  if (!show) return null;
  return (
    <div className="ann-bar">
      <strong>Free prepaid shipping</strong> Australia-wide
      <span className="ann-sep">|</span>Beat any advertised price by <strong>5%</strong>
      <span className="ann-sep">|</span>Paid within <strong>3–5 business days</strong>
    </div>
  );
}

/* ── Navbar ─────────────────────────────────────────────────────────────── */
function Navbar() {
  const megaMenus = [
    {
      label:'Sell Phone',
      cols: [
        { title:'Apple iPhone', items:[['iPhone 17 Pro Max','$1,250'],['iPhone 17 Pro','$1,050'],['iPhone 17','$880'],['iPhone 16 Pro Max','$980'],['iPhone 15 Pro','$580'],['Older iPhones','From $120']] },
        { title:'Samsung Galaxy', items:[['Galaxy S25 Ultra','$1,050'],['Galaxy S25+','$840'],['Galaxy S24 Ultra','$880'],['Galaxy Z Fold 6','$1,100'],['Galaxy Z Flip 6','$640'],['Older Galaxy','From $90']] },
        { title:'Other Brands', items:[['Google Pixel','Up to $780'],['OnePlus','Up to $480'],['OPPO','Up to $420'],['Sony Xperia','Up to $520'],['Motorola','Up to $300'],['Other Android','From $80']] },
      ],
      feat: { eyebrow:'Top price this week', title:'iPhone 17 Pro Max', desc:'Get up to $1,250 — paid in 3–5 business days.', cta:'Get my quote →' },
    },
    {
      label:'Sell Tablet',
      cols: [
        { title:'Apple iPad', items:[['iPad Pro 13" M4','$1,250'],['iPad Pro 11" M4','$980'],['iPad Air M2','$680'],['iPad Mini 7','$480'],['iPad 10th Gen','$340'],['Older iPads','From $80']] },
        { title:'Samsung & MS', items:[['Galaxy Tab S10 Ultra','$780'],['Galaxy Tab S10+','$580'],['Surface Pro 11','$880'],['Surface Pro 10','$660'],['Tab S9 series','$420'],['Older models','From $80']] },
        { title:'Other', items:[['Lenovo Tab','Up to $320'],['Huawei MatePad','Up to $280'],['Xiaomi Pad','Up to $240'],['Amazon Fire HD','Up to $80'],['Other Android','From $40']] },
      ],
      feat: { eyebrow:'Pro tip', title:'iPad Pro M4 holds 78% value', desc:'Newer iPads keep their value longer than any other tablet.', cta:'Sell yours →' },
    },
    {
      label:'Sell Watch',
      cols: [
        { title:'Apple Watch', items:[['Watch Ultra 2','$580'],['Series 10','$380'],['Series 9','$300'],['Watch SE 3','$220'],['Older Watch','From $60']] },
        { title:'Samsung & Garmin', items:[['Galaxy Watch Ultra','$380'],['Galaxy Watch 7','$280'],['Galaxy Watch 6','$200'],['Garmin Fenix 8','$520'],['Garmin Epix Pro','$400']] },
        { title:'Fitness & Other', items:[['Fitbit Sense 2','$120'],['Fitbit Versa 4','$95'],['Polar','Up to $180'],['Suunto','Up to $220'],['Other','From $40']] },
      ],
      feat: { eyebrow:'Free shipping', title:'Insured up to $1,500', desc:'Send your watch with peace of mind via Australia Post.', cta:'Get a quote →' },
    },
    {
      label:'Sell Laptop',
      cols: [
        { title:'Apple MacBook', items:[['MacBook Pro 16" M4','$2,200'],['MacBook Pro 14" M4','$1,900'],['MacBook Air 15" M3','$1,380'],['MacBook Air 13" M3','$1,160'],['Older MacBooks','From $300']] },
        { title:'Windows', items:[['Dell XPS 15','$680'],['Dell XPS 13','$520'],['HP Spectre x360','$580'],['ThinkPad X1 Carbon','$680'],['Yoga 9i','$480']] },
        { title:'Gaming & Other', items:[['ROG Zephyrus G14','$680'],['ASUS ZenBook 14','$380'],['HP Envy 14','$380'],['Surface Laptop','Up to $720'],['Other Laptops','From $200']] },
      ],
      feat: { eyebrow:'Max value', title:'MacBooks pay the most', desc:'Get up to $2,200 for current-gen MacBook Pro models.', cta:'Sell my Mac →' },
    },
  ];
  return (
    <nav className="navbar">
      <div className="navbar-inner">
        <a href="TekRevive.html" className="logo" aria-label="TekRevive"><img src="logo.svg" alt="TekRevive" /></a>
        <div className="nav-links">
          {megaMenus.map(m => (
            <div key={m.label} className="nav-drop">
              <a href={m.label === 'Sell Phone' ? 'Sell iPhone.html' : 'Sell Your Phone.html'}>{m.label} <span className="nav-caret">▾</span></a>
              <div className="mega-menu">
                {m.cols.map(c => (
                  <div key={c.title}>
                    <div className="mega-col-title">{c.title}</div>
                    {c.items.map(([n,p]) => (
                      <a key={n} href={productHref(n, /iphone/i.test(n) ? 'Apple' : '')} className="mega-link">
                        <span>{n}</span><span className="mega-link-price">{p}</span>
                      </a>
                    ))}
                  </div>
                ))}
                <a href={productHref(m.feat.title, /iphone/i.test(m.feat.title) ? 'Apple' : '')} className="mega-feat">
                  <div>
                    <div className="mega-feat-eyebrow">{m.feat.eyebrow}</div>
                    <div className="mega-feat-title">{m.feat.title}</div>
                    <div className="mega-feat-desc">{m.feat.desc}</div>
                  </div>
                  <span className="mega-feat-cta">{m.feat.cta}</span>
                </a>
              </div>
            </div>
          ))}
          <a href="#how">How It Works</a>
          <a href="#faq">FAQ</a>
        </div>
        <div className="nav-actions">
          <button className="btn-ghost">Buy Refurbished</button>
          <a href="Sell Your Phone.html" className="btn-cta">Get Instant Quote →</a>
        </div>
      </div>
    </nav>
  );
}

/* ── Brands Bar ─────────────────────────────────────────────────────────── */
function BrandsBar() {
  const brands = ['Apple','Samsung','Google','OnePlus','Oppo','Huawei','Motorola','Sony','Xiaomi','LG','Nothing'];
  return (
    <div className="brands-bar">
      <div className="brands-lbl">We buy devices from all major brands</div>
      <div className="brands-row">
        {brands.map(b => <button key={b} className="brand-pill">{b}</button>)}
      </div>
    </div>
  );
}

/* ── Product Image Placeholder ──────────────────────────────────────────── */
function DeviceThumb({ type, brand, name }) {
  const palettes = {
    Apple:   { bg1:'#e8edf4', bg2:'#d2dae6', body:'#bdc6d4', screen:'#dde4ef', shine:'rgba(255,255,255,.55)', accent:'#a8b4c4' },
    Samsung: { bg1:'#e4eaf6', bg2:'#ccd6ec', body:'#9aaad0', screen:'#dde5f8', shine:'rgba(255,255,255,.5)',  accent:'#8899cc' },
    Google:  { bg1:'#f0eef8', bg2:'#ddd9f0', body:'#a89fd4', screen:'#edeaf8', shine:'rgba(255,255,255,.5)',  accent:'#9080cc' },
  };
  const p = palettes[brand] || palettes.Apple;

  const PhoneSvg = () => (
    <svg width="54" height="86" viewBox="0 0 54 86" fill="none">
      {/* body shadow */}
      <rect x="5" y="4" width="44" height="78" rx="9" fill={p.accent} opacity=".35" transform="translate(1,2)"/>
      {/* body */}
      <rect x="5" y="3" width="44" height="78" rx="9" fill={p.body}/>
      {/* side sheen */}
      <rect x="5" y="3" width="8" height="78" rx="9" fill={p.shine} opacity=".4"/>
      {/* screen bezel */}
      <rect x="8" y="7" width="38" height="68" rx="6" fill={p.accent}/>
      {/* screen */}
      <rect x="9" y="8" width="36" height="66" rx="5.5" fill={p.screen}/>
      {/* screen glare */}
      <rect x="9" y="8" width="22" height="26" rx="5.5" fill={p.shine} opacity=".5"/>
      {/* dynamic island */}
      <rect x="19" y="11" width="16" height="5" rx="2.5" fill={p.body}/>
      {/* home indicator */}
      <rect x="20" y="70" width="14" height="2.5" rx="1.25" fill={p.accent}/>
      {/* side button */}
      <rect x="49" y="24" width="3" height="10" rx="1.5" fill={p.accent}/>
      {/* volume buttons */}
      <rect x="2" y="22" width="3" height="7" rx="1.5" fill={p.accent}/>
      <rect x="2" y="32" width="3" height="7" rx="1.5" fill={p.accent}/>
    </svg>
  );

  const LaptopSvg = () => (
    <svg width="100" height="72" viewBox="0 0 100 72" fill="none">
      {/* lid shadow */}
      <rect x="7" y="3" width="86" height="54" rx="5" fill={p.accent} opacity=".3" transform="translate(1,2)"/>
      {/* lid */}
      <rect x="7" y="3" width="86" height="54" rx="5" fill={p.body}/>
      {/* lid sheen */}
      <rect x="7" y="3" width="20" height="54" rx="5" fill={p.shine} opacity=".35"/>
      {/* screen bezel */}
      <rect x="11" y="7" width="78" height="46" rx="3" fill={p.accent}/>
      {/* screen */}
      <rect x="12" y="8" width="76" height="44" rx="2.5" fill={p.screen}/>
      {/* screen glare */}
      <rect x="12" y="8" width="38" height="18" rx="2.5" fill={p.shine} opacity=".45"/>
      {/* camera dot */}
      <circle cx="50" cy="6.5" r="1.2" fill={p.accent}/>
      {/* base */}
      <rect x="0" y="59" width="100" height="10" rx="4" fill={p.body}/>
      <rect x="0" y="59" width="20" height="10" rx="4" fill={p.shine} opacity=".3"/>
      {/* notch under lid */}
      <rect x="36" y="57" width="28" height="3" rx="1.5" fill={p.accent}/>
      {/* trackpad */}
      <rect x="36" y="62" width="28" height="5" rx="2" fill={p.accent} opacity=".5"/>
    </svg>
  );

  const TabletSvg = () => (
    <svg width="64" height="82" viewBox="0 0 64 82" fill="none">
      <rect x="3" y="3" width="58" height="76" rx="8" fill={p.accent} opacity=".3" transform="translate(1,2)"/>
      <rect x="3" y="3" width="58" height="76" rx="8" fill={p.body}/>
      <rect x="3" y="3" width="12" height="76" rx="8" fill={p.shine} opacity=".4"/>
      <rect x="7" y="7" width="50" height="68" rx="5" fill={p.accent}/>
      <rect x="8" y="8" width="48" height="66" rx="4.5" fill={p.screen}/>
      <rect x="8" y="8" width="26" height="28" rx="4.5" fill={p.shine} opacity=".45"/>
      <circle cx="32" cy="79" r="2" fill={p.accent}/>
      <circle cx="32" cy="5" r="1.5" fill={p.accent}/>
      <rect x="61" y="24" width="3" height="14" rx="1.5" fill={p.accent}/>
    </svg>
  );

  const WatchSvg = () => (
    <svg width="56" height="76" viewBox="0 0 56 76" fill="none">
      {/* band top */}
      <rect x="16" y="0" width="24" height="18" rx="4" fill={p.accent} opacity=".7"/>
      <rect x="16" y="0" width="8" height="18" rx="4" fill={p.shine} opacity=".3"/>
      {/* band bottom */}
      <rect x="16" y="58" width="24" height="18" rx="4" fill={p.accent} opacity=".7"/>
      {/* case shadow */}
      <rect x="5" y="16" width="46" height="44" rx="13" fill={p.accent} opacity=".3" transform="translate(1,2)"/>
      {/* case */}
      <rect x="5" y="16" width="46" height="44" rx="13" fill={p.body}/>
      <rect x="5" y="16" width="10" height="44" rx="13" fill={p.shine} opacity=".4"/>
      {/* screen */}
      <rect x="9" y="20" width="38" height="36" rx="10" fill={p.screen}/>
      {/* screen glare */}
      <rect x="9" y="20" width="22" height="16" rx="10" fill={p.shine} opacity=".5"/>
      {/* crown */}
      <rect x="51" y="28" width="4" height="10" rx="2" fill={p.accent}/>
      {/* time display hint */}
      <rect x="17" y="32" width="22" height="4" rx="2" fill={p.accent} opacity=".4"/>
      <rect x="20" y="39" width="16" height="3" rx="1.5" fill={p.accent} opacity=".25"/>
    </svg>
  );

  const icons = { phone:<PhoneSvg/>, laptop:<LaptopSvg/>, tablet:<TabletSvg/>, watch:<WatchSvg/> };

  return (
    <div style={{
      width:'100%', height:'120px', borderRadius:'var(--r-md)', marginBottom:'16px',
      background: `linear-gradient(145deg, ${p.bg1} 0%, ${p.bg2} 100%)`,
      display:'flex', alignItems:'center', justifyContent:'center',
      position:'relative', overflow:'hidden',
    }}>
      {/* subtle grid texture */}
      <div style={{ position:'absolute', inset:0, backgroundImage:'radial-gradient(circle, rgba(255,255,255,.6) 1px, transparent 1px)', backgroundSize:'18px 18px', opacity:.5 }}></div>
      <div style={{ position:'relative', zIndex:1, filter:'drop-shadow(0 4px 10px rgba(0,0,0,.12))' }}>
        {icons[type] || <PhoneSvg/>}
      </div>
    </div>
  );
}

/* ── Product page routing ─────────────────────────────────────────────── */
function productHref(name, brand) {
  // Dedicated product pages
  if (name === 'iPhone 17 Pro Max') return 'Sell iPhone 17 Pro Max.html';
  if (name === 'iPhone 16 Pro Max') return 'Sell iPhone 16 Pro Max.html';
  if (name === 'iPhone 15 Pro Max') return 'Sell iPhone 15 Pro Max.html';
  // Other iPhones → generic iPhone landing
  if (brand === 'Apple' && /iphone/i.test(name)) return 'Sell iPhone.html';
  // Everything else → generic phone landing
  return 'Sell Your Phone.html';
}

/* ── Popular Models ─────────────────────────────────────────────────────── */
function PopularModels() {
  const models = [
    { brand:'Apple',   name:'iPhone 17 Pro Max', price:'$1,250', badge:'New',  type:'phone'  },
    { brand:'Apple',   name:'iPhone 17 Pro',     price:'$1,050', badge:'New',  type:'phone'  },
    { brand:'Apple',   name:'iPhone 16 Pro Max', price:'$980',                 type:'phone'  },
    { brand:'Apple',   name:'iPhone 16 Pro',     price:'$820',                 type:'phone'  },
    { brand:'Apple',   name:'iPhone 15 Pro Max', price:'$720',                 type:'phone'  },
    { brand:'Apple',   name:'iPhone 15 Pro',     price:'$580',                 type:'phone'  },
    { brand:'Samsung', name:'Galaxy S25 Ultra',  price:'$1,050',               type:'phone'  },
    { brand:'Google',  name:'Pixel 9 Pro',       price:'$680',                 type:'phone'  },
  ];
  return (
    <section className="sec" style={{ background:'var(--light)' }}>
      <div className="sec-inner">
        <div className="reveal" style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:'32px', flexWrap:'wrap', gap:'12px' }}>
          <div>
            <div className="eyebrow">Top prices this week</div>
            <h2 className="sec-title" style={{ marginBottom:0 }}>Most popular trade-ins</h2>
          </div>
          <a href="Sell Your Phone.html" style={{ color:'var(--blue)', fontWeight:600, fontSize:'14px' }}>See all models →</a>
        </div>
        <div className="models-grid">
          {models.map((m, i) => (
            <div key={m.name} className={`model-card reveal rev-d${Math.min(i%4+1,3)}`}>
              {m.badge && <span className="model-badge">{m.badge}</span>}
              <DeviceThumb type={m.type} brand={m.brand} />
              <div className="model-brand">{m.brand}</div>
              <div className="model-name">{m.name}</div>
              <div className="model-up-to">Up to</div>
              <div className="model-price">{m.price}</div>
              <a href={productHref(m.name, m.brand)} className="model-btn" style={{ display:'block', textAlign:'center', textDecoration:'none', color:'white' }}>Get Quote</a>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ── Why Section ────────────────────────────────────────────────────────── */
function WhySection() {
  const Check = () => (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
      <path d="M3 9l4.5 4.5L15 5" stroke="#FEC20E" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
  const items = [
    { title:'Price Beat Guarantee', desc:'Find a better price anywhere in Australia and we\'ll beat it by 5%. Every time, guaranteed.' },
    { title:'Fast Payment',         desc:'Bank transfer or PayPal within 3–5 business days of receiving your device. No delays.' },
    { title:'Free Prepaid Shipping',desc:'Prepaid Australia Post satchel emailed instantly. Drop at any post office — zero cost.' },
    { title:'Risk-Free Returns',    desc:'Not happy with the final offer? We\'ll return your device free of charge, no questions.' },
  ];
  return (
    <section className="sec" id="why">
      <div className="sec-inner">
        <div className="why-layout">
          {/* LEFT — copy + image */}
          <div className="reveal-left">
            <div className="eyebrow">Why TekRevive</div>
            <h2 className="sec-title">The smarter way<br />to sell your tech</h2>
            <p className="sec-desc" style={{ marginBottom:'28px' }}>Built on fairness, speed and transparency. No hidden fees, no lowball offers.</p>
            <a href="Sell Your Phone.html" className="btn-cta" style={{ marginBottom:'36px' }}>Start Selling →</a>

            <div style={{ position:'relative', borderRadius:'var(--r-lg)', overflow:'hidden', boxShadow:'0 24px 64px rgba(0,0,0,.14)' }}>
              <img
                src="https://images.unsplash.com/photo-1512054502232-10a0a035d672?w=800&q=80&auto=format&fit=crop"
                alt="iPhone close-up"
                style={{ width:'100%', height:'340px', objectFit:'cover', display:'block' }}
                loading="lazy"
              />
              <div style={{ position:'absolute', inset:0, background:'linear-gradient(to top, rgba(31,37,45,.55) 0%, transparent 60%)' }}></div>
              <div style={{ position:'absolute', bottom:'18px', left:'20px', right:'20px', display:'flex', alignItems:'center', gap:'10px' }}>
                <div style={{ width:'34px', height:'34px', borderRadius:'8px', background:'var(--yellow)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M12 2L3 7v6c0 5.25 3.75 10.15 9 11.35C17.25 23.15 21 18.25 21 13V7L12 2z" stroke="#1F252D" strokeWidth="2.2" strokeLinejoin="round"/></svg>
                </div>
                <div>
                  <div style={{ fontSize:'12px', color:'rgba(255,255,255,.75)', fontWeight:600, letterSpacing:'.04em', textTransform:'uppercase' }}>Trusted by 50,000+ Aussies</div>
                  <div style={{ fontSize:'15px', color:'#fff', fontWeight:700, marginTop:'2px' }}>4.9 / 5 on Google Reviews</div>
                </div>
              </div>
            </div>
          </div>

          {/* RIGHT — 4 reasons stacked */}
          <div className="reveal why-grid">
            {items.map(item => (
              <div key={item.title} className="why-card">
                <div className="why-icon"><Check /></div>
                <div><div className="why-title">{item.title}</div><div className="why-desc">{item.desc}</div></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ── How It Works ───────────────────────────────────────────────────────── */
function HowItWorks() {
  const steps = [
    {
      n:'1', title:'Get Your Quote', time:'~60 seconds',
      desc:'Pick your device, brand, model, condition. Get an instant estimated trade-in value.',
      bullets:['No sign-up required','Browse 1,000+ models','Locked-in price for 14 days'],
      icon:<svg width="28" height="28" viewBox="0 0 28 28" fill="none"><circle cx="12" cy="12" r="7" stroke="#263D89" strokeWidth="2"/><path d="M17.5 17.5L23 23" stroke="#263D89" strokeWidth="2" strokeLinecap="round"/></svg>,
    },
    {
      n:'2', title:'Ship It Free', time:'2–3 days',
      desc:'We email you a prepaid Australia Post satchel. Pack securely and drop at any post office.',
      bullets:['Free prepaid shipping','Insurance up to $1,500','Track every step in real-time'],
      icon:<svg width="28" height="28" viewBox="0 0 28 28" fill="none"><path d="M3 9l11-5 11 5v10l-11 5-11-5V9z" stroke="#263D89" strokeWidth="2" strokeLinejoin="round"/><path d="M3 9l11 5 11-5M14 14v10" stroke="#263D89" strokeWidth="2"/></svg>,
    },
    {
      n:'3', title:'Get Paid Fast', time:'3–5 days',
      desc:'After inspection we transfer to your bank or PayPal — fast, secure, no surprises.',
      bullets:['Bank transfer or PayPal','+10% bonus as store credit','Risk-free return if unhappy'],
      icon:<svg width="28" height="28" viewBox="0 0 28 28" fill="none"><rect x="3" y="7" width="22" height="14" rx="2" stroke="#263D89" strokeWidth="2"/><circle cx="14" cy="14" r="3" stroke="#263D89" strokeWidth="2"/><path d="M3 11h22" stroke="#263D89" strokeWidth="2"/></svg>,
    },
  ];
  return (
    <section className="sec" style={{ background:'var(--light)' }} id="how">
      <div className="sec-inner">
        <div className="sec-head ctr reveal">
          <div className="eyebrow">How it works</div>
          <h2 className="sec-title">Three steps to getting paid</h2>
          <p className="sec-desc">Simple, safe, stress-free. Most sellers complete the process in under 5 minutes.</p>
        </div>
        <div className="how-grid">
          {steps.map((s, i) => (
            <div key={s.n} className={`how-card reveal rev-d${i+1}`} style={{ display:'flex', flexDirection:'column' }}>
              <div style={{ display:'flex', alignItems:'center', gap:'12px', marginBottom:'14px' }}>
                <div className="how-step" style={{ margin:0 }}>{s.n}</div>
                <div style={{
                  display:'inline-flex', alignItems:'center', gap:'5px',
                  fontSize:'11px', fontWeight:700, color:'var(--blue)',
                  background:'rgba(38,61,137,.08)', padding:'4px 10px', borderRadius:'999px',
                  textTransform:'uppercase', letterSpacing:'.05em',
                }}>
                  <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><circle cx="5" cy="5" r="4" stroke="currentColor" strokeWidth="1.3"/><path d="M5 3v2l1.5 1" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>
                  {s.time}
                </div>
                <div style={{ marginLeft:'auto', opacity:.55 }}>{s.icon}</div>
              </div>
              <div className="how-title">{s.title}</div>
              <div className="how-desc" style={{ marginBottom:'14px' }}>{s.desc}</div>
              <ul style={{ listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap:'7px', borderTop:'1px solid var(--border)', paddingTop:'14px' }}>
                {s.bullets.map(b => (
                  <li key={b} style={{ display:'flex', alignItems:'center', gap:'8px', fontSize:'13px', color:'var(--primary)', fontWeight:500 }}>
                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" style={{ flexShrink:0 }}>
                      <circle cx="6.5" cy="6.5" r="6" fill="rgba(254,194,14,.25)"/>
                      <path d="M3.5 6.5l2.2 2.2L9.5 4.5" stroke="#263D89" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                    {b}
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ── About ──────────────────────────────────────────────────────────────── */
function AboutSection() {
  return (
    <section className="sec" id="about">
      <div className="sec-inner">
        <div className="about-layout">
          <div className="reveal-left">
            <div className="eyebrow">Who we are</div>
            <h2 className="sec-title">Aussie-owned.<br />Planet-focused.</h2>
            <p className="sec-desc" style={{ marginBottom:'18px' }}>TekRevive is a proud Australian company helping everyday Aussies turn unused tech into real value. We're not a marketplace — we're a trusted trade-in partner putting people and the planet first.</p>
            <p className="sec-desc" style={{ marginBottom:'28px' }}>Every device recycled means one less in landfill. Good for your wallet, good for the planet.</p>
            <div className="about-minis">
              {[['$422M+','Paid to Australians'],['50,000+','Devices recycled'],['10+','Years in business']].map(([n,l]) => (
                <div key={l}><div className="about-mini-num">{n}</div><div className="about-mini-label">{l}</div></div>
              ))}
            </div>
          </div>
          <div className="reveal-right" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gridTemplateRows:'1fr 1fr', gap:'10px', height:'340px' }}>
            <image-slot id="about-1" placeholder="Team / office photo" shape="rounded" radius="12" style={{ width:'100%', height:'100%' }}></image-slot>
            <image-slot id="about-2" placeholder="Warehouse shot" shape="rounded" radius="12" style={{ width:'100%', height:'100%' }}></image-slot>
            <image-slot id="about-3" placeholder="Device inspection" shape="rounded" radius="12" style={{ width:'100%', height:'100%' }}></image-slot>
            <image-slot id="about-4" placeholder="Packaging / shipping" shape="rounded" radius="12" style={{ width:'100%', height:'100%' }}></image-slot>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ── Stats Band (with count-up) ─────────────────────────────────────────── */
function StatItem({ num, suffix, label }) {
  const ref = useRef(); const [active, setActive] = useState(false);
  const count = useCountUp(num, active);
  useEffect(() => {
    const obs = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setActive(true); obs.disconnect(); } }, { threshold:.5 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return (
    <div ref={ref} className="stat-item">
      <div className="stat-num">{active ? count.toLocaleString() : 0}{suffix}</div>
      <div className="stat-label">{label}</div>
    </div>
  );
}

function StatsBand() {
  return (
    <div className="stats-band">
      <div className="stats-grid">
        <StatItem num={422} suffix="M+" label="Paid out to date ($)" />
        <StatItem num={50000} suffix="+" label="Devices purchased" />
        <div className="stat-item"><div className="stat-num">4.9 / 5</div><div className="stat-label">Google rating</div></div>
        <StatItem num={10} suffix="+" label="Years experience" />
      </div>
    </div>
  );
}

/* ── Avatar initials ────────────────────────────────────────────────────── */
function Avatar({ name, color }) {
  const initials = name.split(' ').map(w => w[0]).join('').slice(0,2).toUpperCase();
  const colors = ['#263D89','#263D89','#2d6a4f','#6d3a8f','#b85c2a'];
  const bg = color || colors[name.charCodeAt(0) % colors.length];
  return (
    <div style={{
      width:'40px', height:'40px', borderRadius:'50%', background:bg,
      display:'flex', alignItems:'center', justifyContent:'center',
      fontSize:'14px', fontWeight:700, color:'#fff', flexShrink:0,
      letterSpacing:'-.01em',
    }}>{initials}</div>
  );
}

/* ── Testimonials ───────────────────────────────────────────────────────── */
function Testimonials() {
  const reviews = [
    { text:'"Always a great experience — fast, super reliable, and completely trustworthy. I\'ve sent phones through the mail multiple times and always received constant updates."', author:'Sarah M.', device:'Sold iPhone 15 Pro Max', stars:5 },
    { text:'"Honestly the best trade-in price on the market. The experience was seamless and professional from start to finish. Payment arrived exactly when they said it would."', author:'James T.', device:'Sold Galaxy S24 Ultra', stars:5 },
    { text:'"Didn\'t want the hassle of Facebook Marketplace. TekRevive made it so easy — got a quote online, shipped the next day, and had cash in my account two days later."', author:'Michelle K.', device:'Sold Google Pixel 9 Pro', stars:5 },
  ];
  return (
    <section className="sec" id="reviews" style={{ background:'var(--light)' }}>
      <div className="sec-inner">
        <div className="sec-head ctr reveal">
          <div className="eyebrow">Customer reviews</div>
          <h2 className="sec-title">Trusted by thousands of Australians</h2>
          <p className="sec-desc">Don't just take our word for it.</p>
        </div>
        <div className="testi-grid">
          {reviews.map((r, i) => (
            <div key={r.author} className={`testi-card reveal rev-d${i+1}`}>
              <div className="testi-stars" style={{ display:'flex', gap:'2px' }}>
                {Array.from({length: r.stars}).map((_,i) => (
                  <svg key={i} width="14" height="14" viewBox="0 0 24 24" fill="#FEC20E"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>
                ))}
              </div>
              <p className="testi-text">{r.text}</p>
              <div style={{ display:'flex', alignItems:'center', gap:'10px', marginTop:'auto' }}>
                <image-slot id={`avatar-${i}`} placeholder="Photo" shape="circle" style={{ width:'40px', height:'40px', flexShrink:0 }}></image-slot>
                <div>
                  <div className="testi-author">{r.author}</div>
                  <div className="testi-device">{r.device}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ── FAQ ────────────────────────────────────────────────────────────────── */
function FAQ() {
  const [open, setOpen] = useState(null);
  const faqs = [
    { q:'How do I get paid?', a:'We pay via bank transfer (EFT) or PayPal within 3–5 business days of receiving and inspecting your device. You\'ll receive an email confirmation as soon as payment is sent.' },
    { q:'What do "As New", "Working" and "Dead" mean?', a:'"As New" — no scratches or damage, perfect condition. "Working" — some visible wear but fully functional. "Dead" — no longer usable, includes water damage or devices that won\'t turn on.' },
    { q:'Do you accept cracked or broken devices?', a:'Yes! We accept Working and Dead condition devices. Even broken devices have parts value. You\'ll still get a fair price based on the actual condition.' },
    { q:'What if my device condition differs from what I selected?', a:'We\'ll contact you with a revised offer. You can accept the new offer or have your device returned free of charge — completely your choice.' },
    { q:'Why do you need my IMEI number?', a:'Your IMEI lets us verify the device is not lost, stolen or network-blocked. This protects both you and us. You can find your IMEI by dialling *#06# or checking Settings > About.' },
    { q:'How do I ship my device?', a:'After completing your sell order, we\'ll email you a prepaid Australia Post satchel label. Pack it securely, remove personal data, and sign out of all accounts before sending.' },
    { q:'Can I drop off in person?', a:'Yes! Level 4 / 306 Little Collins Street, Melbourne VIC 3000. Mon–Fri 9am–6pm. Create a sell order online first, then bring your device in.' },
  ];
  const Chev = ({ o }) => (
    <svg className={'faq-chevron'+(o?' open':'')} width="18" height="18" viewBox="0 0 18 18" fill="none">
      <path d="M4 7l5 5 5-5" stroke="#4B545D" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
  return (
    <section className="sec" id="faq">
      <div className="sec-inner">
        <div className="faq-layout">
          <div className="reveal-left">
            <div className="eyebrow">FAQ</div>
            <h2 className="sec-title">Common questions</h2>
            <p className="sec-desc" style={{ marginBottom:'20px' }}>Can't find what you need?</p>
            <a href="#" style={{ color:'var(--blue)', fontWeight:600, fontSize:'14px' }}>Contact our team →</a>
          </div>
          <div className="faq-list reveal-right">
            {faqs.map((f,i) => (
              <div key={i} className="faq-item">
                <button className="faq-q" onClick={() => setOpen(open===i?null:i)}>{f.q}<Chev o={open===i}/></button>
                {open===i && <div className="faq-a">{f.a}</div>}
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ── CTA ────────────────────────────────────────────────────────────────── */
function CTASection() {
  const secRef = useRef(null);
  const bgRef  = useRef(null);
  useEffect(() => {
    const onScroll = () => {
      if (!secRef.current || !bgRef.current) return;
      const rect = secRef.current.getBoundingClientRect();
      const pct  = Math.max(0, Math.min(1, (window.innerHeight - rect.top) / (window.innerHeight + rect.height)));
      bgRef.current.style.transform = `translateY(${(pct - 0.5) * 60}px)`;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <section ref={secRef} className="cta-sec" style={{ position:'relative', overflow:'hidden', padding:'110px 32px', textAlign:'center' }}>
      {/* Parallax layer */}
      <div ref={bgRef} style={{ position:'absolute', inset:'-60px', willChange:'transform', pointerEvents:'none' }}>
        {/* dot grid */}
        <div style={{ position:'absolute', inset:0, backgroundImage:'radial-gradient(rgba(254,194,14,.06) 1.5px, transparent 1.5px)', backgroundSize:'32px 32px' }}></div>
        {/* diagonal lines */}
        <svg style={{ position:'absolute', inset:0, width:'100%', height:'100%', opacity:.04 }} xmlns="http://www.w3.org/2000/svg">
          <defs><pattern id="ctaLines" width="40" height="40" patternUnits="userSpaceOnUse" patternTransform="rotate(35)">
            <line x1="0" y1="0" x2="0" y2="40" stroke="#FEC20E" strokeWidth="1"/>
          </pattern></defs>
          <rect width="100%" height="100%" fill="url(#ctaLines)"/>
        </svg>
        {/* floating device outlines */}
        {[{x:'8%',y:'12%',r:-18,s:0.7},{x:'88%',y:'10%',r:14,s:0.55},{x:'5%',y:'68%',r:12,s:0.5},{x:'92%',y:'72%',r:-22,s:0.65},{x:'50%',y:'5%',r:8,s:0.4}].map((pos,i) => (
          <div key={i} style={{ position:'absolute', left:pos.x, top:pos.y, transform:`rotate(${pos.r}deg) scale(${pos.s})`, opacity:.06 }}>
            <svg width="54" height="86" viewBox="0 0 54 86" fill="none"><rect x="5" y="3" width="44" height="78" rx="9" stroke="#FEC20E" strokeWidth="3"/><rect x="9" y="8" width="36" height="66" rx="5.5" stroke="#FEC20E" strokeWidth="1.5"/><rect x="19" y="11" width="16" height="5" rx="2.5" fill="#FEC20E"/></svg>
          </div>
        ))}
        {/* glow orbs */}
        <div style={{ position:'absolute', top:'-10%', left:'20%', width:'500px', height:'500px', borderRadius:'50%', background:'radial-gradient(circle, rgba(254,194,14,.07) 0%, transparent 70%)' }}></div>
        <div style={{ position:'absolute', bottom:'-20%', right:'15%', width:'420px', height:'420px', borderRadius:'50%', background:'radial-gradient(circle, rgba(38,61,137,.1) 0%, transparent 70%)' }}></div>
      </div>
      {/* Content */}
      <div className="cta-inner reveal" style={{ position:'relative', zIndex:1, maxWidth:'680px', margin:'0 auto' }}>
        <div style={{ display:'inline-flex', alignItems:'center', gap:'8px', background:'rgba(254,194,14,.1)', border:'1px solid rgba(254,194,14,.2)', borderRadius:'999px', padding:'6px 16px', marginBottom:'22px' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M12 2L3 7v6c0 5.25 3.75 10.15 9 11.35C17.25 23.15 21 18.25 21 13V7L12 2z" stroke="#FEC20E" strokeWidth="2" strokeLinejoin="round"/></svg>
          <span style={{ fontSize:'12px', fontWeight:700, letterSpacing:'.06em', textTransform:'uppercase', color:'#FEC20E' }}>Australia&apos;s #1 Tech Buyback</span>
        </div>
        <h2 className="cta-title">Ready to <em>revive your tech?</em></h2>
        <p className="cta-sub">Join thousands of Australians who&apos;ve turned old devices into real cash.</p>
        <div style={{ display:'flex', justifyContent:'center', gap:'12px', flexWrap:'wrap' }}>
          <a href="Sell Your Phone.html" className="btn-cta" style={{ fontSize:'16px', padding:'15px 40px' }}>Get My Quote Now →</a>
          <a href="#how" style={{ display:'inline-flex', alignItems:'center', gap:'8px', padding:'15px 28px', border:'1.5px solid rgba(255,255,255,.2)', borderRadius:'var(--r-xl)', fontSize:'15px', fontWeight:600, color:'rgba(255,255,255,.75)', transition:'all .15s' }}
            onMouseEnter={e => { e.currentTarget.style.borderColor='rgba(255,255,255,.5)'; e.currentTarget.style.color='white'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor='rgba(255,255,255,.2)'; e.currentTarget.style.color='rgba(255,255,255,.75)'; }}>
            How It Works
          </a>
        </div>
        {/* mini trust strip */}
        <div style={{ display:'flex', justifyContent:'center', gap:'24px', marginTop:'36px', flexWrap:'wrap' }}>
          {[
            [<svg key="s" width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M12 2L3 7v6c0 5.25 3.75 10.15 9 11.35C17.25 23.15 21 18.25 21 13V7L12 2z" stroke="rgba(255,255,255,.45)" strokeWidth="2" strokeLinejoin="round"/></svg>, 'Price-beat guarantee'],
            [<svg key="t" width="14" height="14" viewBox="0 0 24 24" fill="none"><rect x="1" y="10" width="15" height="8" rx="1" stroke="rgba(255,255,255,.45)" strokeWidth="2"/><path d="M16 13h4l3 4H16v-4z" stroke="rgba(255,255,255,.45)" strokeWidth="2" strokeLinejoin="round"/><circle cx="5.5" cy="18.5" r="1.5" fill="rgba(255,255,255,.45)"/><circle cx="18.5" cy="18.5" r="1.5" fill="rgba(255,255,255,.45)"/></svg>, 'Free prepaid shipping'],
            [<svg key="c" width="14" height="14" viewBox="0 0 24 24" fill="none"><rect x="2" y="5" width="20" height="14" rx="2" stroke="rgba(255,255,255,.45)" strokeWidth="2"/><path d="M2 10h20" stroke="rgba(255,255,255,.45)" strokeWidth="2"/></svg>, 'Paid in 3–5 days'],
          ].map(([icon,label]) => (
            <div key={label} style={{ display:'flex', alignItems:'center', gap:'7px', fontSize:'13px', fontWeight:500, color:'rgba(255,255,255,.4)' }}>
              {icon}{label}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ── Newsletter ─────────────────────────────────────────────────────────── */
function Newsletter() {
  const [email, setEmail] = useState(''); const [done, setDone] = useState(false);
  return (
    <div className="news-sec">
      <div className="news-inner reveal">
        <h3 className="news-title">Stay ahead of the market</h3>
        <p className="news-sub">Get price alerts and exclusive trade-in deals before they change.</p>
        {done ? <p style={{ color:'var(--blue)', fontWeight:600 }}>Thanks — you're on the list.</p>
          : <div className="news-form">
              <input className="news-input" type="email" placeholder="Your email address" value={email} onChange={e => setEmail(e.target.value)}/>
              <button className="news-btn" onClick={() => email && setDone(true)}>Subscribe</button>
            </div>}
      </div>
    </div>
  );
}

/* ── Footer ─────────────────────────────────────────────────────────────── */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div>
          <a href="TekRevive.html" className="logo logo-footer" aria-label="TekRevive"><img src="logo-light.svg" alt="TekRevive" /></a>
          <p className="footer-desc">Australia's trusted tech buyback platform. Turning old devices into real value since 2014. Proudly Melbourne-based.</p>
          <p className="footer-addr">Level 4 / 306 Little Collins St<br/>Melbourne VIC 3000<br/>Mon–Fri 9am–6pm AEST</p>
        </div>
        <div>
          <div className="footer-col-lbl">Sell</div>
          <div className="footer-links">
            <a href="Sell iPhone.html">Sell iPhone</a>
            <a href="Sell Your Phone.html">Sell Your Phone</a>
            <a href="Sell Your Phone.html">Sell Your Tablet</a>
            <a href="Sell Your Phone.html">Sell Your Watch</a>
            <a href="Sell Your Phone.html">Sell Your Laptop</a>
            <a href="#">Buy Refurbished</a>
          </div>
        </div>
        <div>
          <div className="footer-col-lbl">Company</div>
          <div className="footer-links">
            <a href="#how">How It Works</a>
            <a href="#">Price Beat Guarantee</a>
            <a href="#">Phones For Homes</a>
            <a href="#">Drop-Off Option</a>
          </div>
        </div>
        <div>
          <div className="footer-col-lbl">Help</div>
          <div className="footer-links">
            <a href="#faq">FAQ</a>
            <a href="#">Contact Us</a>
            <a href="#">Your Privacy Matters</a>
            <a href="#">Terms &amp; Conditions</a>
          </div>
        </div>
      </div>
      <div className="footer-bottom">
        <span className="footer-copy">© 2026 TekRevive Pty Ltd. ABN 12 345 678 901. All rights reserved.</span>
        <div className="footer-badges">
          <span className="footer-badge">SSL Secured</span>
          <span className="footer-badge">ACCC Compliant</span>
          <span className="footer-badge">Australia Post Partner</span>
        </div>
      </div>
    </footer>
  );
}

/* ── App ────────────────────────────────────────────────────────────────── */
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useScrollReveal();

  useEffect(() => {
    document.documentElement.style.setProperty('--yellow', t.accentColor);
    document.documentElement.style.setProperty('--yellow-hover', t.accentColor === '#FEC20E' ? '#E5AE0C' : t.accentColor + 'cc');
  }, [t.accentColor]);

  return (
    <>
      <AnnBar show={t.showBanner} />
      <Navbar />
      <Hero heroSize={t.heroSize} />
      <BrandsBar />
      <PopularModels />
      <WhySection />
      <HowItWorks />
      <StatsBand />
      <Testimonials />
      <FAQ />
      <CTASection />
      <Footer />
      <TweaksPanel>
        <TweakSection label="Brand Colour" />
        <TweakColor label="Accent" value={t.accentColor} options={['#FEC20E','#263D89','#22c55e','#e85d3e']} onChange={v => setTweak('accentColor', v)} />
        <TweakSection label="Layout" />
        <TweakToggle label="Announcement bar" value={t.showBanner} onChange={v => setTweak('showBanner', v)} />
        <TweakRadio label="Hero size" value={t.heroSize} options={['full','compact']} onChange={v => setTweak('heroSize', v)} />
      </TweaksPanel>
    </>
  );
}

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