/* QZ Motors — real enquiry forms. Every submission is composed into an email to the showroom
   (no backend in this prototype), plus an optional WhatsApp hand-off. No fake success states. */
const FDS = window.QZMotorsDesignSystem_756851;
const {Button:FBtn, Input:FInput, Select:FSelect, Switch:FSwitch, Modal:FModal, Toast:FToast} = FDS;
const {useState:fS, useEffect:fE} = React;

const QZ_EMAIL='qzmotorsg8@gmail.com';
const QZ_WA='923125815615';
const YEARS_F=Array.from({length:30},(_,i)=>String(2026-i));

/* Opens an external URL at the top level — inside a preview iframe an in-frame
   navigation to WhatsApp is blocked, so escape to the top window / a new tab. */
function openExternal(url){
  try{ const w=window.open(url,'_blank','noopener'); if(w){w.opener=null; return;} }catch(e){}
  try{ window.top.location.href=url; return; }catch(e){}
  window.location.href=url;
}
function sendMail(subject, fields){
  const body=Object.entries(fields).filter(([,v])=>v!=='' && v!=null).map(([k,v])=>`${k}: ${v}`).join('\n');
  window.location.href=`mailto:${QZ_EMAIL}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
}
function sendWhatsApp(subject, fields){
  const body=Object.entries(fields).filter(([,v])=>v!=='' && v!=null).map(([k,v])=>`${k}: ${v}`).join('\n');
  const url=`https://wa.me/${QZ_WA}?text=${encodeURIComponent(subject+'\n'+body)}`;
  openExternal(url);
}

/* Shared shell: label, required-field gating, DB save (with email/WhatsApp hand-off) */
function EnquiryForm({subject, fields, valid, onSent, children, note, table, row}){
  const [busy,setBusy]=fS(false);
  const [err,setErr]=fS('');
  const save=async(e)=>{
    e.preventDefault();
    if(!valid||busy) return;
    if(!table||!window.QZDB.configured){ sendMail(subject, fields); onSent('email'); return; }
    setBusy(true); setErr('');
    try{ await window.QZDB.insert(table, row); onSent('saved'); }
    catch(ex){ setErr(ex.message+' — you can still send it as an email.'); }
    finally{ setBusy(false); }
  };
  return (
    <form className="qz-form qz-form-modal" onSubmit={save}>
      <div className="qz-form-scroll">
        {children}
        {note && <p className="qz-form-note">{note}</p>}
        {err && <p className="qz-form-note" role="alert" style={{color:'var(--color-primary)'}}>{err}</p>}
      </div>
      <div className="qz-form-actions">
        <FBtn variant="outline-dark" type="button" disabled={!valid} onClick={()=>{if(valid){sendWhatsApp(subject,fields); onSent('whatsapp');}}}>Send on WhatsApp</FBtn>
        <FBtn type="submit" disabled={!valid||busy}>{busy?'Saving…':(table&&window.QZDB.configured?'Submit request':'Send by email')}</FBtn>
      </div>
    </form>
  );
}

/* --- Valuation / trade-in ------------------------------------------------- */
function ValuationModal({open, onClose, onSent, mode='valuation'}){
  const blank={name:'',phone:'',brand:'',model:'',year:'2021',km:'',condition:'Good',city:'Islamabad',target:'',notes:''};
  const [f,setF]=fS(blank);
  const set=(k)=>(e)=>setF({...f,[k]:e.target.value});
  const valid=f.name.trim().length>1 && f.phone.trim().length>=10 && f.brand.trim() && f.model.trim() && f.km!=='';
  const trade=mode==='trade';
  return (
    <FModal open={open} onClose={onClose} title={trade?'Request a trade-in valuation':'Request a valuation'}>
      <EnquiryForm
        subject={(trade?'Trade-in valuation request':'Valuation request')+` — ${f.year} ${f.brand} ${f.model}`}
        valid={valid}
        table={trade?'exchange_requests':'valuation_requests'}
        row={{name:f.name, phone:f.phone, brand:f.brand, model:f.model, year:+f.year, mileage_km:+f.km||null,
          condition:f.condition, city:f.city, notes:f.notes||null, ...(trade?{wanted_vehicle:f.target||null}:{})}}
        onSent={(how)=>{onSent(how); setF(blank); onClose();}}
        note="We value the car against live Islamabad prices and call you back within 24 hours."
        fields={{'Your name':f.name,'Mobile / WhatsApp':f.phone,'Vehicle':`${f.year} ${f.brand} ${f.model}`,'Mileage (KM)':f.km,'Condition':f.condition,'City':f.city,...(trade?{'Car they want from QZ Motors':f.target}:{}),'Notes':f.notes}}>
        <div className="qz-form-grid">
          <FInput label="Your name" value={f.name} onChange={set('name')} required/>
          <FInput label="Mobile / WhatsApp" type="tel" placeholder="+92 3XX XXXXXXX" value={f.phone} onChange={set('phone')} required/>
          <FInput label="Brand" placeholder="Toyota" value={f.brand} onChange={set('brand')} required/>
          <FInput label="Model" placeholder="Corolla Altis" value={f.model} onChange={set('model')} required/>
          <FSelect label="Model year" value={f.year} onChange={set('year')} options={YEARS_F}/>
          <FInput label="Mileage (KM)" type="number" placeholder="42000" value={f.km} onChange={set('km')} required/>
          <FSelect label="Condition" value={f.condition} onChange={set('condition')} options={['Excellent','Good','Average','Needs work']}/>
          <FSelect label="City" value={f.city} onChange={set('city')} options={['Islamabad','Rawalpindi','Lahore','Karachi','Peshawar','Other']}/>
          {trade && <FInput label="Car you want from us" placeholder="2019 Audi Q7" value={f.target} onChange={set('target')}/>}
          <FInput label="Anything else" placeholder="Tyres new, minor scratch on rear bumper" value={f.notes} onChange={set('notes')}/>
        </div>
      </EnquiryForm>
    </FModal>
  );
}

/* --- General showroom enquiry -------------------------------------------- */
function ContactModal({open, onClose, onSent, about=''}){
  const blank={name:'',phone:'',topic:'Buying a car',message:'',time:'Anytime'};
  const [f,setF]=fS(blank);
  const set=(k)=>(e)=>setF({...f,[k]:e.target.value});
  const valid=f.name.trim().length>1 && f.phone.trim().length>=10 && f.message.trim().length>3;
  return (
    <FModal open={open} onClose={onClose} title="Talk to the showroom">
      <EnquiryForm
        subject={'Showroom enquiry — '+(about||f.topic)}
        valid={valid}
        onSent={(how)=>{onSent(how); setF(blank); onClose();}}
        note="Both numbers reach the showroom directly: +92 312 5815615 · +92 318 5747145."
        fields={{'Your name':f.name,'Mobile / WhatsApp':f.phone,'Topic':f.topic,...(about?{'About':about}:{}),'Best time to call':f.time,'Message':f.message}}>
        <div className="qz-form-grid">
          <FInput label="Your name" value={f.name} onChange={set('name')} required/>
          <FInput label="Mobile / WhatsApp" type="tel" placeholder="+92 3XX XXXXXXX" value={f.phone} onChange={set('phone')} required/>
          <FSelect label="What is it about?" value={f.topic} onChange={set('topic')} options={['Buying a car','Selling a car','Trade-in','Inspection report','Documents & transfer','Something else']}/>
          <FSelect label="Best time to call" value={f.time} onChange={set('time')} options={['Anytime','Morning','Afternoon','Evening']}/>
        </div>
        <FInput label="Your message" placeholder="I am looking for a 2019+ SUV under 2 Cr." value={f.message} onChange={set('message')} required/>
      </EnquiryForm>
    </FModal>
  );
}

/* --- Sign in / register (local session; replace with real auth server-side) */
function AuthModal({open, onClose, onSignedIn}){
  const [mode,setMode]=fS('in');
  const [f,setF]=fS({name:'',phone:'',email:'',pass:''});
  const set=(k)=>(e)=>setF({...f,[k]:e.target.value});
  const reg=mode==='up';
  const valid=reg ? (f.name.trim().length>1 && f.phone.trim().length>=10 && f.pass.length>=6) : (f.phone.trim().length>=10 && f.pass.length>=6);
  const submit=(e)=>{
    e.preventDefault(); if(!valid) return;
    const user={name:reg?f.name:(f.phone),phone:f.phone,email:f.email};
    localStorage.setItem('qz-user',JSON.stringify(user));
    onSignedIn(user, reg); onClose();
  };
  return (
    <FModal open={open} onClose={onClose} title={reg?'Create an account':'Sign in'}>
      <form className="qz-form qz-form-modal" onSubmit={submit}>
        <div className="qz-form-scroll">
        <div className="qz-form-grid">
          {reg && <FInput label="Your name" value={f.name} onChange={set('name')} required/>}
          <FInput label="Mobile number" type="tel" placeholder="+92 3XX XXXXXXX" value={f.phone} onChange={set('phone')} required/>
          {reg && <FInput label="Email (optional)" type="email" value={f.email} onChange={set('email')}/>}
          <FInput label="Password" type="password" value={f.pass} onChange={set('pass')} required/>
        </div>
        <p className="qz-form-note">{reg?'Your listings and saved cars stay attached to this number.':'Use the mobile number your listings are under.'}</p>
        </div>
        <div className="qz-form-actions">
          <FBtn variant="outline-dark" type="button" onClick={()=>setMode(reg?'in':'up')}>{reg?'I already have an account':'Create an account'}</FBtn>
          <FBtn type="submit" disabled={!valid}>{reg?'Create account':'Sign in'}</FBtn>
        </div>
      </form>
    </FModal>
  );
}

/* --- Newsletter (real email opt-in via the showroom inbox) ---------------- */
function subscribeEmail(email){
  sendMail('Newsletter subscription',{'Email':email,'Wants':'Weekly new-arrivals email'});
}

Object.assign(window,{openExternal, ValuationModal, ContactModal, AuthModal, EnquiryForm, sendMail, sendWhatsApp, subscribeEmail, QZ_EMAIL, QZ_WA});
