// HausEnquiry — premium multi-step enquiry flow

const STEPS = [
  {
    id: 'type',
    q: 'What are you imagining?',
    sub: 'Pick the one that excites you most. We\'ll figure the rest out together.',
    type: 'cards',
    options: [
      { value: 'climbing-wall', label: 'Climbing wall', desc: 'A statement wall with timber, holds, and rope' },
      { value: 'movement-corner', label: 'Movement corner', desc: 'Bars, ladder, beam — a compact full setup' },
      { value: 'swing-setup', label: 'Swing setup', desc: 'Ceiling-mounted swing or sensory pod' },
      { value: 'custom', label: 'Full custom build', desc: 'Something entirely bespoke' },
      { value: 'unsure', label: 'I\'m not sure yet', desc: 'That\'s what the call is for' },
    ],
  },
  {
    id: 'children',
    q: 'Tell us about your kids.',
    sub: 'This shapes the design — scale, holds, swing height, all of it.',
    type: 'children',
  },
  {
    id: 'budget',
    q: 'Rough budget?',
    sub: 'No commitment — just helps us shape the right design.',
    type: 'cards',
    options: [
      { value: 'under-3k', label: 'Under $3,000', desc: 'Single element, compact' },
      { value: '3-6k', label: '$3,000–$6,000', desc: 'Movement corner or modest climbing wall' },
      { value: '6-10k', label: '$6,000–$10,000', desc: 'Full wall with multiple elements' },
      { value: '10k-plus', label: '$10,000+', desc: 'Custom multi-zone build' },
      { value: 'not-sure', label: 'Not sure', desc: 'Help me understand what\'s realistic' },
    ],
  },
  {
    id: 'suburb',
    q: 'Where are you?',
    sub: 'We install across Perth and surrounds.',
    type: 'text',
    placeholder: 'Suburb or town',
    field: 'suburb',
  },
  {
    id: 'email',
    q: 'How do we reach you?',
    sub: 'We\'ll come back within two business days with first ideas and a ballpark.',
    type: 'contact',
  },
];

const inputBase = {
  width:'100%', fontFamily:"'Montserrat',sans-serif", fontSize:15, fontWeight:400,
  background:'rgba(255,255,255,0.6)', border:'1.5px solid #e8d9c5', borderRadius:12,
  padding:'14px 16px', color:'#1f1f1f',
  transition:'border-color 200ms', boxSizing:'border-box',
};

const OptionCard = ({ opt, selected, onClick }) => (
  <button type="button" className="option-card" onClick={onClick} style={{
    display:'block', width:'100%', textAlign:'left',
    padding:'18px 20px', borderRadius:16, cursor:'pointer',
    background: selected ? '#5a7a4a' : 'rgba(255,255,255,0.5)',
    border: `1.5px solid ${selected ? '#5a7a4a' : '#e8d9c5'}`,
    transition:'background 220ms cubic-bezier(0.25,0.46,0.45,0.94), border-color 220ms cubic-bezier(0.25,0.46,0.45,0.94), box-shadow 220ms cubic-bezier(0.25,0.46,0.45,0.94)',
    boxShadow: 'none',
  }}>
    <div style={{fontFamily:"'Montserrat',sans-serif", fontSize:13, fontWeight:600, color: selected ? '#fff' : '#1f1f1f', marginBottom:4}}>{opt.label}</div>
    <div style={{fontFamily:"'Montserrat',sans-serif", fontSize:11, fontWeight:300, color: selected ? 'rgba(255,255,255,0.75)' : '#9a9088', lineHeight:1.5}}>{opt.desc}</div>
  </button>
);

const SuburbSelect = ({ value, onChange }) => {
  const [suburbs, setSuburbs] = React.useState([]);
  const [inputText, setInputText] = React.useState(value || '');
  const [open, setOpen] = React.useState(false);
  const containerRef = React.useRef();

  React.useEffect(() => {
    fetch('/assets/wa-suburbs.json').then(r => r.json()).then(setSuburbs);
  }, []);

  React.useEffect(() => { setInputText(value || ''); }, [value]);

  const filtered = inputText.length > 0
    ? suburbs.filter(s => s.toLowerCase().includes(inputText.toLowerCase()))
    : suburbs;

  React.useEffect(() => {
    const handler = (e) => {
      if (containerRef.current && !containerRef.current.contains(e.target)) {
        setOpen(false);
        if (!suburbs.includes(inputText)) { setInputText(value || ''); }
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [inputText, value, suburbs]);

  const select = (suburb) => { onChange(suburb); setInputText(suburb); setOpen(false); };

  return (
    <div ref={containerRef} style={{position:'relative', maxWidth:440, margin:'0 auto'}}>
      <input
        className="haus-input"
        style={{...inputBase, paddingRight:40}}
        placeholder={suburbs.length === 0 ? 'Loading…' : 'Search suburb…'}
        disabled={suburbs.length === 0}
        value={inputText}
        name="suburb"
        autoComplete="off"
        spellCheck="false"
        onChange={e => { setInputText(e.target.value); onChange(''); setOpen(true); }}
        onFocus={e => { e.target.style.borderColor='#5a7a4a'; setOpen(true); }}
        onBlur={e => e.target.style.borderColor='#e8d9c5'}
      />
      <svg style={{position:'absolute', right:14, top:'50%', transform:'translateY(-50%)', pointerEvents:'none', opacity:0.4}}
        width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#1f1f1f" strokeWidth="2" strokeLinecap="round">
        <polyline points="6 9 12 15 18 9"/>
      </svg>
      {open && filtered.length > 0 && (
        <div style={{position:'absolute', top:'calc(100% + 4px)', left:0, right:0, zIndex:200,
          background:'#fffaf3', border:'1.5px solid #e8d9c5', borderRadius:12,
          boxShadow:'0 8px 32px rgba(31,24,16,0.12)', maxHeight:220, overflowY:'auto'}}>
          {filtered.slice(0, 30).map(suburb => (
            <button key={suburb} type="button" onMouseDown={() => select(suburb)} style={{
              display:'block', width:'100%', textAlign:'left',
              padding:'11px 16px', fontFamily:"'Montserrat',sans-serif", fontSize:13,
              fontWeight: suburb === value ? 600 : 400,
              color: suburb === value ? '#5a7a4a' : '#1f1f1f',
              background: suburb === value ? 'rgba(90,122,74,0.06)' : 'none',
              border:'none', borderBottom:'1px solid rgba(232,217,197,0.5)', cursor:'pointer',
            }}>{suburb}</button>
          ))}
        </div>
      )}
    </div>
  );
};

const HausEnquiry = ({ enquiryRef }) => {
  const [step, setStep] = React.useState(0);
  const [dir, setDir] = React.useState(1); // 1 = forward, -1 = back
  const [animOut, setAnimOut] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [data, setData] = React.useState({ type:'', numKids:1, ages:[], budget:'', suburb:'', name:'', email:'' });

  const S = STEPS[step];

  const nav = (delta) => {
    setDir(delta);
    setAnimOut(true);
    setTimeout(() => {
      setStep(s => s + delta);
      setAnimOut(false);
    }, 220);
  };

  const submit = () => {
    setAnimOut(true);
    setTimeout(() => { setDone(true); setAnimOut(false); }, 220);
  };

  const set = (k) => (v) => setData(d => ({...d, [k]: v}));

  const canAdvance = () => {
    if (S.id === 'type') return !!data.type;
    if (S.id === 'children') return data.ages.length > 0;
    if (S.id === 'budget') return !!data.budget;
    if (S.id === 'suburb') return data.suburb.trim().length > 1;
    if (S.id === 'email') return data.name.trim().length > 0 && /\S+@\S+\.\S+/.test(data.email);
    return true;
  };

  const slideStyle = {
    opacity: animOut ? 0 : 1,
    transform: animOut ? `translateX(${dir * 24}px)` : 'translateX(0)',
    transition: animOut
      ? 'opacity 200ms ease-in, transform 200ms ease-in'
      : 'opacity 350ms 30ms cubic-bezier(0.25,0.46,0.45,0.94), transform 350ms 30ms cubic-bezier(0.25,0.46,0.45,0.94)',
  };

  const ageOptions = ['Under 2', '2–4', '5–7', '8–10', '11–14', '14+'];
  const toggleAge = (a) => set('ages')(data.ages.includes(a) ? data.ages.filter(x=>x!==a) : [...data.ages, a]);

  if (done) {
    const firstName = data.name.split(' ')[0];
    const typeLabels = { 'climbing-wall':'Climbing wall', 'movement-corner':'Movement corner', 'swing-setup':'Swing setup', 'custom':'Custom build' };
    const contextParts = [typeLabels[data.type], data.suburb].filter(Boolean);
    return (
      <section id="contact" ref={enquiryRef} style={{background:'#f5ede0', padding:'clamp(64px,8vw,120px) clamp(20px,5vw,48px)'}}>
        <div style={{maxWidth:520, margin:'0 auto', textAlign:'center', ...slideStyle}}>
          <div style={{width:52, height:52, borderRadius:'50%', background:'#5a7a4a', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 28px'}}>
            <svg width="22" height="18" viewBox="0 0 24 20" fill="none"><path d="M2 10l7 7L22 2" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </div>
          {contextParts.length > 0 && (
            <div style={{fontFamily:"'Montserrat',sans-serif", fontSize:11, fontWeight:600, letterSpacing:'0.14em', textTransform:'uppercase', color:'#899e7b', marginBottom:16}}>
              {contextParts.join(' · ')}
            </div>
          )}
          <div style={{fontFamily:"'Fonphoria',serif", fontWeight:700, fontSize:'clamp(28px,4vw,44px)', lineHeight:1.1, letterSpacing:'-0.02em', color:'#1f1f1f', marginBottom:20}}>
            We've got it, {firstName}.
          </div>
          <p style={{fontFamily:"'Montserrat',sans-serif", fontSize:14, fontWeight:300, lineHeight:1.85, color:'#5a5248', marginBottom:12}}>
            Your enquiry is on our desk. We'll come back to you within two business days with first ideas drawn to your room — a rough layout, materials, and an honest price.
          </p>
          <p style={{fontFamily:"'Montserrat',sans-serif", fontSize:13, fontWeight:400, lineHeight:1.7, color:'#9a9088', marginBottom:36}}>
            No chasing. No hard sell.
          </p>
          <button onClick={()=>{setDone(false); setStep(0); setData({type:'',numKids:1,ages:[],budget:'',suburb:'',name:'',email:''}); setAnimOut(false);}}
            style={{fontFamily:"'Montserrat',sans-serif", fontSize:12, fontWeight:600, letterSpacing:'0.06em', background:'transparent', color:'#5a5248', border:'1.5px solid #c4b49e', borderRadius:9999, padding:'12px 28px', cursor:'pointer'}}>
            Start another enquiry
          </button>
        </div>
      </section>
    );
  }

  return (
    <section id="contact" ref={enquiryRef} style={{background:'radial-gradient(ellipse 80% 50% at 50% 0%, #e8d3b0 0%, #f5ede0 55%)', padding:'clamp(64px,8vw,120px) clamp(20px,5vw,48px)'}}>
      <div style={{maxWidth:760, margin:'0 auto'}}>
        {/* Header */}
        <div style={{textAlign:'center', marginBottom:48}}>
          <div style={{fontFamily:"'Montserrat',sans-serif", fontSize:11, fontWeight:600, letterSpacing:'0.16em', textTransform:'uppercase', color:'#899e7b', marginBottom:12}}>Start your project</div>
          <h2 style={{fontFamily:"'Fonphoria',serif", fontWeight:700, fontSize:'clamp(28px,3.5vw,44px)', lineHeight:1.05, letterSpacing:'-0.02em', color:'#1f1f1f', marginBottom:0}}>Tell us about your space.</h2>
        </div>

        {/* Progress */}
        <div style={{display:'flex', gap:6, justifyContent:'center', marginBottom:52}}>
          {STEPS.map((_, i) => (
            <div key={i} style={{
              height:3, borderRadius:9999,
              width: i === step ? 28 : 8,
              background: i <= step ? '#5a7a4a' : '#d4c4aa',
              transition:'width 300ms cubic-bezier(0.25,0.46,0.45,0.94), background 300ms cubic-bezier(0.25,0.46,0.45,0.94)',
            }}/>
          ))}
        </div>

        {/* Step content */}
        <div style={{minHeight:300, ...slideStyle}}>
          <div style={{textAlign:'center', marginBottom:36}}>
            <h3 style={{fontFamily:"'Fonphoria',serif", fontWeight:600, fontSize:'clamp(22px,2.5vw,32px)', lineHeight:1.1, letterSpacing:'-0.015em', color:'#1f1f1f', marginBottom:10}}>{S.q}</h3>
            <p style={{fontFamily:"'Montserrat',sans-serif", fontSize:14, fontWeight:300, lineHeight:1.7, color:'#5a5248', maxWidth:440, margin:'0 auto'}}>{S.sub}</p>
          </div>

          {/* CARDS step */}
          {S.type === 'cards' && (
            <div className="option-cards" style={{display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(180px,1fr))', gap:10, maxWidth:680, margin:'0 auto'}}>
              {S.options.map(opt => (
                <OptionCard key={opt.value} opt={opt}
                  selected={S.id==='type' ? data.type===opt.value : data.budget===opt.value}
                  onClick={()=>{S.id==='type' ? set('type')(opt.value) : set('budget')(opt.value);}} />
              ))}
            </div>
          )}

          {/* CHILDREN step */}
          {S.type === 'children' && (
            <div style={{maxWidth:480, margin:'0 auto', display:'flex', flexDirection:'column', gap:24}}>
              <div>
                <label style={{fontFamily:"'Montserrat',sans-serif", fontSize:11, fontWeight:600, letterSpacing:'0.1em', textTransform:'uppercase', color:'#5a5248', display:'block', marginBottom:12}}>Number of children</label>
                <div style={{display:'flex', gap:8}}>
                  {[1,2,3,4,5].map(n=>(
                    <button key={n} onClick={()=>set('numKids')(n)} style={{width:44, height:44, borderRadius:12, fontFamily:"'Montserrat',sans-serif", fontSize:14, fontWeight:600, border:`1.5px solid ${data.numKids===n?'#5a7a4a':'#e8d9c5'}`, background:data.numKids===n?'#5a7a4a':'rgba(255,255,255,0.5)', color:data.numKids===n?'#fff':'#1f1f1f', cursor:'pointer', transition:'background 200ms, border-color 200ms'}}>{n}</button>
                  ))}
                </div>
              </div>
              <div>
                <label style={{fontFamily:"'Montserrat',sans-serif", fontSize:11, fontWeight:600, letterSpacing:'0.1em', textTransform:'uppercase', color:'#5a5248', display:'block', marginBottom:12}}>Age range (select all that apply)</label>
                <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
                  {ageOptions.map(a=>(
                    <button key={a} onClick={()=>toggleAge(a)} style={{padding:'9px 16px', borderRadius:9999, fontFamily:"'Montserrat',sans-serif", fontSize:12, fontWeight:500, border:`1.5px solid ${data.ages.includes(a)?'#5a7a4a':'#e8d9c5'}`, background:data.ages.includes(a)?'#5a7a4a':'rgba(255,255,255,0.5)', color:data.ages.includes(a)?'#fff':'#5a5248', cursor:'pointer', transition:'background 200ms, border-color 200ms'}}>{a}</button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* TEXT step */}
          {S.type === 'text' && (
            <SuburbSelect value={data[S.field]} onChange={set(S.field)} />
          )}

          {/* CONTACT step */}
          {S.type === 'contact' && (
            <div style={{maxWidth:440, margin:'0 auto', display:'flex', flexDirection:'column', gap:14}}>
              <div>
                <label style={{fontFamily:"'Montserrat',sans-serif", fontSize:10, fontWeight:600, letterSpacing:'0.1em', textTransform:'uppercase', color:'#5a5248', display:'block', marginBottom:8}}>Your name</label>
                <input className="haus-input" style={inputBase} placeholder="First and last name" value={data.name}
                  name="name" autoComplete="name"
                  onChange={e=>set('name')(e.target.value)} onFocus={e=>e.target.style.borderColor='#5a7a4a'} onBlur={e=>e.target.style.borderColor='#e8d9c5'} />
              </div>
              <div>
                <label style={{fontFamily:"'Montserrat',sans-serif", fontSize:10, fontWeight:600, letterSpacing:'0.1em', textTransform:'uppercase', color:'#5a5248', display:'block', marginBottom:8}}>Email address</label>
                <input className="haus-input" style={inputBase} type="email" placeholder="your@email.com" value={data.email}
                  name="email" autoComplete="email" spellCheck="false"
                  onChange={e=>set('email')(e.target.value)} onFocus={e=>e.target.style.borderColor='#5a7a4a'} onBlur={e=>e.target.style.borderColor='#e8d9c5'} />
              </div>
            </div>
          )}
        </div>

        {/* Nav buttons */}
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:44}}>
          <button onClick={()=>nav(-1)} disabled={step===0} style={{fontFamily:"'Montserrat',sans-serif", fontSize:12, fontWeight:500, letterSpacing:'0.04em', background:'transparent', color: step===0 ? '#c4b49e' : '#5a5248', border:'none', cursor: step===0 ? 'default' : 'pointer', padding:'8px 0', transition:'color 200ms'}}>
            ← Back
          </button>
          <div style={{fontFamily:"'Montserrat',sans-serif", fontSize:11, fontWeight:500, color:'#9a9088', letterSpacing:'0.06em'}}>{step+1} of {STEPS.length}</div>
          {step < STEPS.length - 1 ? (
            <button onClick={()=>canAdvance() && nav(1)} style={{fontFamily:"'Montserrat',sans-serif", fontSize:13, fontWeight:600, letterSpacing:'0.05em', background: canAdvance() ? '#5a7a4a' : '#d4c4aa', color:'#fff', border:'none', borderRadius:9999, padding:'13px 28px', cursor: canAdvance() ? 'pointer' : 'default', transition:'background 220ms'}}
              onMouseEnter={e=>{ if(canAdvance()) e.currentTarget.style.background='#496840'; }}
              onMouseLeave={e=>{ e.currentTarget.style.background = canAdvance() ? '#5a7a4a' : '#d4c4aa'; }}>
              Continue →
            </button>
          ) : (
            <button onClick={()=>canAdvance() && submit()} style={{fontFamily:"'Montserrat',sans-serif", fontSize:13, fontWeight:600, letterSpacing:'0.05em', background: canAdvance() ? '#5a7a4a' : '#d4c4aa', color:'#fff', border:'none', borderRadius:9999, padding:'13px 28px', cursor: canAdvance() ? 'pointer' : 'default', transition:'background 220ms'}}
              onMouseEnter={e=>{ if(canAdvance()) e.currentTarget.style.background='#496840'; }}
              onMouseLeave={e=>{ e.currentTarget.style.background = canAdvance() ? '#5a7a4a' : '#d4c4aa'; }}>
              Submit enquiry
            </button>
          )}
        </div>
      </div>
      <style>{`
        .haus-input { outline: none; }
        .haus-input:focus-visible { outline: 2px solid #5a7a4a; outline-offset: 0; box-shadow: 0 0 0 4px rgba(90,122,74,0.15); }
        .option-card:focus-visible { outline: 2px solid #5a7a4a; outline-offset: 2px; border-radius: 16px; }
        @media(max-width:500px) { .option-cards { grid-template-columns: 1fr 1fr !important; } }
      `}</style>
    </section>
  );
};
Object.assign(window, { HausEnquiry, OptionCard });
