var {useState,useEffect,useRef} = React;

/* ============================================================
   CONTACT
   ============================================================ */
function Field({id,label,type="text",value,onChange,error,touched,textarea,onBlur,options,min,max,maxLength,autoComplete}){
  const [focus,setFocus]=useState(false);
  const filled=value && value.length>0;
  const active=focus||filled;
  const cls=`field ${active?'active':''} ${error&&touched?'error':''} ${focus?'focus':''}`;
  return (
    <div className={cls}>
      <label htmlFor={id}>{label}</label>
      {textarea ? (
        <textarea id={id} value={value} rows="4" maxLength={maxLength}
          onFocus={()=>setFocus(true)} onBlur={()=>{setFocus(false);onBlur&&onBlur();}}
          onChange={e=>onChange(e.target.value)}/>
      ) : options ? (
        <select id={id} value={value} onFocus={()=>setFocus(true)} onBlur={()=>{setFocus(false);onBlur&&onBlur();}}
          onChange={e=>onChange(e.target.value)}>
          <option value="" disabled hidden></option>
          {options.map(o=><option key={o} value={o}>{o}</option>)}
        </select>
      ) : (
        <input id={id} type={type} value={value} min={min} max={max} maxLength={maxLength} autoComplete={autoComplete}
          onFocus={()=>setFocus(true)} onBlur={()=>{setFocus(false);onBlur&&onBlur();}}
          onChange={e=>onChange(e.target.value)}/>
      )}
      <span className="field-line"></span>
      {error&&touched && <span className="field-err"><window.Icon name="close" size={12}/> {error}</span>}
    </div>
  );
}

const TODAY=new Date().toISOString().split('T')[0];

function ContactForm(){
  const [f,setF]=useState({name:"",email:"",dest:"",when:"",travellers:"",budget:"",msg:""});
  const [touched,setTouched]=useState({});
  const [sent,setSent]=useState(false);
  const set=(k)=>(v)=>setF(p=>({...p,[k]:v}));
  const blur=(k)=>()=>setTouched(p=>({...p,[k]:true}));

  const errors={
    name: !f.name.trim()?"Tell us your name":f.name.trim().length<2?"That seems short":"",
    email: !f.email.trim()?"We need an email to reply":!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email)?"Check that email address":"",
    dest: !f.dest.trim()?"Where are you dreaming of?":"",
    when: f.when&&f.when<TODAY?"Travel dates can't be in the past":"",
    msg: !f.msg.trim()?"A line or two about the trip":f.msg.trim().length<10?"A little more detail helps":"",
  };
  const valid=!errors.name&&!errors.email&&!errors.dest&&!errors.when&&!errors.msg;

  const submit=(e)=>{
    e.preventDefault();
    setTouched({name:true,email:true,dest:true,when:true,msg:true});
    if(valid){
      const message =
        `Hi LaLaLand\n\n`+
        `I'd like to enquire about a trip.\n\n`+
        `Name: ${f.name}\n`+
        `Destination: ${f.dest}\n`+
        `Travel Dates: ${f.when||'Flexible'}\n`+
        `No. of Travellers: ${f.travellers||'Not specified'}\n`+
        `Budget per Person: ${f.budget||'Not specified'}\n`+
        (f.msg.trim()?`\nMore about the trip: ${f.msg.trim()}\n`:``)+
        `\nPlease share the available options and pricing.\n\n`+
        `Thank you.`;
      window.openWA(message);
      setSent(true);
    }
  };

  if(sent){
    return (
      <div className="form-sent">
        <span className="sent-ico"><window.Icon name="check" size={34}/></span>
        <h3 className="h2" style={{marginTop:24}}>It's on its way.</h3>
        <p className="lead col-moss" style={{marginTop:12,maxWidth:'42ch'}}>
          Thanks {f.name.split(' ')[0]}: we've opened WhatsApp with your enquiry. Send it over and a LaLaLand planner will reply within one working day to start shaping {f.dest}.
        </p>
        <button className="btn ghost" style={{marginTop:30}} onClick={()=>{setSent(false);setF({name:"",email:"",dest:"",when:"",travellers:"",budget:"",msg:""});setTouched({});}}>
          <span>Send another</span>
        </button>
      </div>
    );
  }

  return (
    <form className="cform" onSubmit={submit} noValidate>
      <div className="cform-row">
        <Field id="name" label="Your name" value={f.name} onChange={set('name')} onBlur={blur('name')} error={errors.name} touched={touched.name} maxLength={100}/>
        <Field id="email" label="Email address" type="email" value={f.email} onChange={set('email')} onBlur={blur('email')} error={errors.email} touched={touched.email}/>
      </div>
      <div className="cform-row">
        <Field id="dest" label="Where to?" value={f.dest} onChange={set('dest')} onBlur={blur('dest')} error={errors.dest} touched={touched.dest}/>
        <Field id="when" label="Rough dates" type="date" value={f.when} onChange={set('when')} onBlur={blur('when')} error={errors.when} touched={touched.when} autoComplete="off"/>
      </div>
      <div className="cform-row">
        <Field id="travellers" label="Travellers" value={f.travellers} onChange={set('travellers')}
          options={["Solo","2 travellers","Family (3–5)","Group (6+)"]}/>
        <Field id="budget" label="Budget per person" value={f.budget} onChange={set('budget')}
          options={["Economy","Comfort","Premium","Luxury","Not sure yet"]}/>
      </div>
      <Field id="msg" label="Tell us about the trip you're imagining" textarea value={f.msg} onChange={set('msg')} onBlur={blur('msg')} error={errors.msg} touched={touched.msg} maxLength={2000}/>
      <div className="cform-foot">
        <span className="mono cform-note">We reply within 1 working day · No spam, ever</span>
        <button type="submit" className="btn terra">
          <span>Send enquiry <window.Icon name="arrow" size={17} className="arrow"/></span>
        </button>
      </div>
    </form>
  );
}

/* live street-level map */
function MapPanel(){
  const ref=window.useReveal({threshold:.3});
  const ADDR="100 Feet Road, Indiranagar, Bengaluru 560038";
  const q=encodeURIComponent(ADDR);
  // query the full business name + address so Google drops a marker on the listing
  const embed=`https://maps.google.com/maps?q=${encodeURIComponent('LaLaLand Holidays, 100 Feet Road, Indiranagar, Bengaluru 560038')}&z=18&hl=en&output=embed`;
  const directions=`https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent('LaLaLand Holidays, Indiranagar, Bengaluru')}`;
  return (
    <div ref={ref} className="map-panel reveal fade">
      <div className="map-canvas">
        <iframe className="map-frame" src={embed} title="LaLaLand Studio: Indiranagar, Bengaluru"
          loading="lazy" referrerPolicy="no-referrer-when-downgrade" allowFullScreen></iframe>
        <div className="map-card">
          <strong>LaLaLand Studio</strong>
          <span>100ft Road, Indiranagar<br/>Bengaluru 560038, India</span>
          <a className="map-dir textlink" href={directions} target="_blank" rel="noopener">
            Get directions <window.Icon name="arrow" size={14} className="arrow"/>
          </a>
          <a className="map-dir textlink" href={window.GOOGLE_URL} target="_blank" rel="noopener" style={{marginTop:8}}>
            <window.Icon name="google" size={14}/> Reviews on Google
          </a>
        </div>
      </div>
    </div>
  );
}

function ContactInfo(){
  const rows=[
    {ic:"mail",l:"Email",v:"sales@lalalandholidays.com",href:"mailto:sales@lalalandholidays.com"},
    {ic:"wa",l:"WhatsApp",v:window.WA_DISPLAY,href:window.waLink("Hi LaLaLand! I'd like to plan a trip.")},
    {ic:"phone",l:"Call us",v:window.WA_DISPLAY,href:"tel:+"+window.WA_NUMBER},
    {ic:"clock",l:"Hours",v:"Mon–Sat · 10:00–19:00 IST",href:null},
  ];
  return (
    <div className="cinfo">
      {rows.map((r,i)=>(
        <window.Reveal key={r.l} delay={i*70} className="cinfo-row">
          <span className="cinfo-ico"><window.Icon name={r.ic} size={18}/></span>
          <div>
            <span className="mono cinfo-l">{r.l}</span>
            {r.href? <a href={r.href} target={r.href.startsWith('http')?"_blank":undefined} rel={r.href.startsWith('http')?"noopener":undefined} className="cinfo-v textlink">{r.v}</a> : <span className="cinfo-v">{r.v}</span>}
          </div>
        </window.Reveal>
      ))}
      <div className="cinfo-soc">
        {['insta','fb','linkedin','google','wa'].map(s=>{
          const ext = s==='wa' ? window.waLink("Hi LaLaLand! I'd like to plan a trip.") : window.SOC_URL[s];
          return (
            <a key={s} href={ext} target="_blank" rel="noopener"
              className="soc-ico dark-soc" aria-label={s==='google'?'Google':s==='linkedin'?'LinkedIn':s}>
              <window.SocialIcon name={s} size={24}/>
            </a>
          );
        })}
      </div>
    </div>
  );
}

window.ContactPage = function({navigate}){
  return (
    <div className="page-pad contact">
      <section className="ct-hero">
        <div className="wrap">
          <h1 className="display ct-hero-title">
            <span className="tline"><span style={{transitionDelay:'.1s'}}>Let's build</span></span>
            <span className="tline"><span style={{transitionDelay:'.2s'}}>something <em className="serif-it tcolor">unforgettable.</em></span></span>
          </h1>
        </div>
      </section>

      <section className="section tight">
        <div className="wrap">
          <div className="ct-grid">
            <div className="ct-left">
              <window.Reveal variant="fade">
                <h2 className="h3" style={{maxWidth:'24ch'}}>Tell us a little about the journey you have in mind. The more you share, the better we plan.</h2>
              </window.Reveal>
              <div style={{marginTop:30}}><ContactInfo/></div>
            </div>
            <div className="ct-right">
              <window.Reveal variant="fade"><ContactForm/></window.Reveal>
            </div>
          </div>
        </div>
      </section>

      <section className="section tight" style={{paddingTop:0}}>
        <div className="wrap"><MapPanel/></div>
      </section>
    </div>
  );
};

/* ============================================================
   CONTACT STYLES
   ============================================================ */
(function(){
  if(document.getElementById('ct-style'))return;
  const s=document.createElement('style');s.id='ct-style';
  s.textContent=`
.ct-hero{padding:clamp(40px,7vw,90px) 0 clamp(20px,3vw,40px)}
.ct-hero-title{margin-top:20px;max-width:18ch}
.ct-grid{display:grid;grid-template-columns:.85fr 1.15fr;gap:60px;align-items:start}
@media(max-width:900px){.ct-grid{grid-template-columns:1fr;gap:40px}}

/* contact info */
.cinfo-row{display:flex;gap:16px;align-items:flex-start;padding:16px 0;border-top:1px solid var(--line)}
.cinfo-row:first-child{border-top:none}
.cinfo-ico{width:44px;height:44px;border-radius:12px;background:var(--paper-2);color:var(--terra);
  display:flex;align-items:center;justify-content:center;flex:0 0 auto;border:1px solid var(--line)}
.cinfo-l{display:block;font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--moss);margin-bottom:4px}
.cinfo-v{font-size:17px;font-weight:600}
.cinfo-soc{display:flex;gap:18px;margin-top:24px}
.soc-ico.dark-soc{color:var(--ink-soft)}
.soc-ico.dark-soc:hover{color:var(--terra)}

/* form */
.cform-row{display:grid;grid-template-columns:1fr 1fr;gap:22px}
@media(max-width:560px){.cform-row{grid-template-columns:1fr}}
.field{position:relative;padding-top:22px;margin-bottom:24px}
.field label{position:absolute;left:0;top:30px;font-size:16px;color:var(--moss);pointer-events:none;
  transition:all .35s var(--ease-out);font-weight:500}
.field.active label{top:0;font-size:12px;letter-spacing:.06em;color:var(--moss);font-family:'JetBrains Mono',monospace;text-transform:uppercase}
.field.focus label{color:var(--terra)}
.field.error label{color:#d4503a}
.field input,.field textarea,.field select{width:100%;border:none;background:transparent;font-size:17px;font-weight:500;
  color:var(--ink);padding:8px 0;outline:none;border-bottom:1.5px solid var(--line-strong);resize:none}
.field select{cursor:pointer;appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' fill='none' stroke='%235d688c' stroke-width='2'%3E%3Cpath d='M3 5l4 4 4-4'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 4px center}
.field-line{position:absolute;left:0;bottom:0;height:1.5px;width:100%;background:var(--terra);transform:scaleX(0);
  transform-origin:left;transition:transform .45s var(--ease-out)}
.field.focus .field-line{transform:scaleX(1)}
.field.error input,.field.error textarea,.field.error select{border-bottom-color:#d4503a}
.field:not(.active) input[type="date"]{color:transparent}
.field:not(.active) input[type="date"]::-webkit-datetime-edit{color:transparent}
.field-err{position:absolute;right:0;bottom:-20px;font-size:12px;color:#d4503a;display:inline-flex;align-items:center;gap:4px;font-weight:500}
.cform-foot{display:flex;justify-content:space-between;align-items:center;gap:20px;margin-top:14px;flex-wrap:wrap}
.cform-note{font-size:12px;color:var(--moss);letter-spacing:.04em}

/* sent state */
.form-sent{display:flex;flex-direction:column;align-items:flex-start;padding:30px 0;animation:fadeUp .6s var(--ease-out)}
.sent-ico{width:78px;height:78px;border-radius:50%;background:var(--terra);color:#fff;
  display:flex;align-items:center;justify-content:center;box-shadow:0 16px 40px -12px rgba(245,151,30,.5)}

/* map */
.map-panel{border-radius:24px;overflow:hidden;box-shadow:var(--shadow-lg)}
.map-canvas{position:relative;aspect-ratio:21/8;min-height:340px}
.map-frame{position:absolute;inset:0;width:100%;height:100%;border:0;display:block}
.map-card{position:absolute;left:30px;bottom:28px;background:rgba(255,255,255,.94);backdrop-filter:blur(12px);
  border-radius:16px;padding:20px 24px;box-shadow:var(--shadow);max-width:300px;display:flex;flex-direction:column;gap:5px;z-index:2}
.map-card strong{font-size:17px}
.map-card span{font-size:14px;color:var(--moss);line-height:1.45}
.map-dir{font-size:13px!important;margin-top:8px;display:inline-flex;align-items:center;gap:6px;font-weight:600}
.map-dir .arrow{transition:transform .3s var(--ease-out)}
.map-dir:hover .arrow{transform:translateX(3px)}
@media(max-width:560px){.map-card{left:16px;right:16px;bottom:16px;max-width:none}}
`;
  document.head.appendChild(s);
})();
