/* AKMBD Website — Sections: Intro, Services, Studio, Contact */

/* ---------------- Intro statement ---------------- */
function Intro() {
  return (
    <section style={{ background:'var(--surface-0)', padding:'clamp(72px,10vw,140px) 0' }}>
      <div style={{ maxWidth:1320, margin:'0 auto', padding:'0 clamp(20px,5vw,48px)' }}>
        <div className="akm-intro-grid" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'clamp(32px,6vw,90px)', alignItems:'start' }}>
          <Reveal>
            <Eyebrow>The Firm</Eyebrow>
            <p style={{ fontFamily:'var(--font-display)', fontWeight:400, textTransform:'uppercase', color:'var(--ink-1)',
              fontSize:'clamp(24px,2.9vw,40px)', lineHeight:1.22, letterSpacing:'0.02em', marginTop:24, textWrap:'balance' }}>
              Design and construction under one roof. Beauty, functionality, and value engineering.
            </p>
          </Reveal>
          <Reveal delay={80} style={{ paddingTop:'clamp(0px,3vw,40px)' }}>
            <p className="akm-body-lg" style={{ marginBottom:18 }}>
              We start by identifying the client&rsquo;s vision, then bring the resources to turn that vision into a
              tangible plan, and build it. A single team carries each project from first sketch to final walkthrough.
            </p>
            <p className="akm-body">
              AKM Building &amp; Design has delivered custom residential and complex commercial work across
              Southern California. You can relax and watch as your vision comes to life, on time and on budget.
            </p>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Services (numbered rows) ---------------- */
function ServiceRow({ s }) {
  const [h, setH] = useState(false);
  return (
    <div className="akm-svc-row" onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)}
      style={{ display:'grid', gridTemplateColumns:'72px 1fr', gap:'clamp(12px,3vw,40px)', alignItems:'start',
        padding:'clamp(22px,3vw,34px) 0', borderTop:'1px solid var(--line-2)',
        background: h ? 'var(--surface-1)' : 'transparent', transition:'background .25s' }}>
      <span style={{ fontFamily:'var(--font-display)', fontSize:14, letterSpacing:'0.1em', paddingTop:4, color: h?'var(--accent)':'var(--ink-4)', transition:'color .25s' }}>{s.n}</span>
      <div style={{ maxWidth:680 }}>
        <h3 className="akm-h3" style={{ color: h?'var(--accent)':'var(--ink-1)', transition:'color .25s', marginBottom:'clamp(8px,1vw,12px)' }}>{s.t}</h3>
        <p className="akm-body" style={{ margin:0 }}>{s.d}</p>
      </div>
    </div>
  );
}

function Services() {
  return (
    <section id="services" style={{ background:'var(--surface-0)', padding:'clamp(64px,9vw,120px) 0', borderTop:'1px solid var(--line-1)' }}>
      <div style={{ maxWidth:1320, margin:'0 auto', padding:'0 clamp(20px,5vw,48px)' }}>
        <div className="akm-svc-grid" style={{ display:'grid', gridTemplateColumns:'0.62fr 1.38fr', gap:'clamp(28px,4vw,64px)' }}>
          <div className="akm-svc-head" style={{ position:'sticky', top:104, alignSelf:'start' }}>
            <Reveal>
              <Eyebrow>What We Do</Eyebrow>
              <h2 className="akm-h1" style={{ marginTop:18 }}>Services</h2>
              <p className="akm-body" style={{ marginTop:20, maxWidth:300 }}>
                Design, build, and everything in between, all handled by one accountable team.
              </p>
            </Reveal>
          </div>
          <div>
            {AKM_SERVICES.map(s => <ServiceRow key={s.n} s={s} />)}
            <div style={{ borderTop:'1px solid var(--line-2)' }}></div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Studio (light/dark toggle) ---------------- */
function Studio({ dark = true }) {
  const bg = dark ? 'var(--akm-indigo-900)' : 'var(--surface-1)';
  const ink = dark ? '#fff' : 'var(--ink-1)';
  const body = dark ? 'rgba(255,255,255,.78)' : 'var(--ink-2)';
  const eb = dark ? 'var(--akm-indigo-300)' : 'var(--accent)';
  const line = dark ? 'var(--line-on-dark)' : 'var(--line-2)';
  return (
    <section id="studio" style={{ background:bg, padding:'clamp(72px,10vw,132px) 0', overflow:'hidden', position:'relative' }}>
      <div aria-hidden="true" style={{ position:'absolute', top:0, bottom:0, right:0, width:'52%', pointerEvents:'none',
        opacity: dark?0.3:0.22,
        WebkitMaskImage:'linear-gradient(to right, transparent 0%, #000 44%)',
        maskImage:'linear-gradient(to right, transparent 0%, #000 44%)' }}>
        <img src={RES('sketchOffice','assets/sketch-office-interior.png')} alt="" aria-hidden="true"
          style={{ width:'100%', height:'100%', objectFit:'cover', objectPosition:'center',
            filter: dark?'invert(1)':'none', mixBlendMode: dark?'screen':'multiply' }} />
      </div>
      <div style={{ position:'relative', maxWidth:1320, margin:'0 auto', padding:'0 clamp(20px,5vw,48px)' }}>
        <div className="akm-studio-grid" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'clamp(32px,6vw,90px)', alignItems:'center' }}>
          <Reveal>
            <Eyebrow color={eb}>The Studio</Eyebrow>
            <h2 className="akm-h1" style={{ color:ink, marginTop:18, fontSize:'clamp(28px, 3.4vw, 46px)' }}>A single team,<br/>sketch to<br/>walkthrough</h2>
            <p className="akm-body-lg" style={{ color:body, marginTop:24, maxWidth:520 }}>
              AKM Building &amp; Design holds both a State General Contracting license and a State
              Electrical Contracting license. We act as a partner and steward of your vision, managing pre-construction,
              design, and construction so the intent survives every decision.
            </p>
            <p className="akm-body" style={{ color:body, marginTop:16, maxWidth:520 }}>
              We&rsquo;ll either manage your team or bring our own, whatever helps your project get built with value and quality.
            </p>
          </Reveal>
          <Reveal delay={80}>
            <div style={{ display:'grid', gridTemplateColumns:'1fr', gap:0 }}>
              {AKM_STATS.map((st, i) => (
                <div key={i} style={{ display:'flex', alignItems:'baseline', gap:'clamp(16px,3vw,32px)',
                  padding:'clamp(18px,2.6vw,28px) 0', borderTop:`1px solid ${line}`, ...(i===AKM_STATS.length-1?{borderBottom:`1px solid ${line}`}:{}) }}>
                  <span style={{ fontFamily:'var(--font-display)', fontWeight:400, fontSize:'clamp(34px,4.6vw,60px)',
                    letterSpacing:'0.02em', color:ink, lineHeight:1, flex:'0 0 auto', width:'2.6ch', textAlign:'right' }}>{st.v}</span>
                  <span style={{ fontFamily:'var(--font-body)', fontSize:15, color:body, lineHeight:1.4 }}>{st.l}</span>
                </div>
              ))}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Contact (soft form) ---------------- */
function Field({ label, name, type = 'text', value, onChange, onBlur, placeholder, options, rows, error, required, autoComplete, inputMode }) {
  const [focus, setFocus] = useState(false);
  const invalid = !!error;
  const base = {
    width:'100%', fontFamily:'var(--font-body)', fontSize:16, color:'var(--ink-1)', background:'var(--surface-0)',
    border:'1px solid', borderColor: invalid ? 'var(--danger)' : (focus ? 'var(--accent)' : 'var(--line-2)'), borderRadius:2,
    padding:'14px 16px', outline:'none', transition:'border-color .2s',
    boxShadow: focus ? (invalid ? '0 0 0 3px rgba(168,57,47,0.12)' : '0 0 0 3px rgba(53,48,146,0.12)') : 'none',
  };
  const common = {
    name, value,
    onChange: e => onChange(e.target.value),
    onFocus: () => setFocus(true),
    onBlur: () => { setFocus(false); if (onBlur) onBlur(); },
    'aria-invalid': invalid || undefined,
  };
  return (
    <label style={{ display:'block' }}>
      <span style={{ display:'block', fontFamily:'var(--font-display)', fontSize:11, letterSpacing:'0.16em',
        textTransform:'uppercase', color:'var(--ink-3)', marginBottom:9 }}>
        {label}{required && <span style={{ color:'var(--danger)' }}> *</span>}
      </span>
      {options ? (
        <select {...common} style={base}>
          {placeholder && <option value="" disabled>{placeholder}</option>}
          {options.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      ) : rows ? (
        <textarea {...common} placeholder={placeholder} rows={rows} style={{ ...base, resize:'vertical', lineHeight:1.55 }} />
      ) : (
        <input {...common} type={type} placeholder={placeholder} autoComplete={autoComplete} inputMode={inputMode} style={base} />
      )}
      {invalid && (
        <span role="alert" style={{ display:'block', marginTop:6, fontFamily:'var(--font-body)', fontSize:12.5, color:'var(--danger)' }}>{error}</span>
      )}
    </label>
  );
}

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const digitsOf = (s) => (s || '').replace(/\D/g, '');

function fieldError(k, v) {
  const val = (v == null ? '' : String(v)).trim();
  if (k === 'name')  return val ? '' : 'Please enter your name.';
  if (k === 'email') return !val ? 'Please enter your email address.' : (EMAIL_RE.test(val) ? '' : 'Please enter a valid email address.');
  if (k === 'phone') return !val ? 'Please enter your phone number.' : (digitsOf(val).length >= 10 ? '' : 'Please enter a valid phone number.');
  if (k === 'kind')  return val ? '' : 'Please choose a project type.';
  if (k === 'msg')   return val ? '' : 'Please tell us a little about the project.';
  return '';
}

function ContactForm() {
  const [f, setF] = useState({ name:'', email:'', phone:'', kind:'', msg:'', hp:'' });
  const [errors, setErrors] = useState({});
  const [touched, setTouched] = useState({});
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState('');

  const set = (k) => (v) => {
    setF(prev => ({ ...prev, [k]:v }));
    if (touched[k]) setErrors(prev => ({ ...prev, [k]: fieldError(k, v) }));
  };
  const blur = (k) => () => {
    setTouched(prev => ({ ...prev, [k]:true }));
    setErrors(prev => ({ ...prev, [k]: fieldError(k, f[k]) }));
  };

  const attemptSubmit = async () => {
    if (submitting) return;
    const errs = {};
    ['name','email','phone','kind','msg'].forEach(k => { const e = fieldError(k, f[k]); if (e) errs[k] = e; });
    setTouched({ name:true, email:true, phone:true, kind:true, msg:true });
    setErrors(errs);
    if (Object.keys(errs).length) return;
    if (f.hp) { setSent(true); return; }        // honeypot filled -> silently drop (bot)
    setSubmitError('');
    setSubmitting(true);
    try {
      const res = await fetch('/api/lead', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: f.name, email: f.email, phone: f.phone,
          projectType: f.kind, message: f.msg,
          company_website: f.hp, pageUrl: window.location.href,
        }),
      });
      if (!res.ok) throw new Error('status ' + res.status);
      setSent(true);
    } catch (err) {
      setSubmitting(false);
      setSubmitError('Sorry — something went wrong sending your message. Please try again, or call us directly.');
    }
  };

  if (sent) {
    return (
      <div style={{ border:'1px solid var(--line-2)', padding:'clamp(32px,5vw,56px)', background:'var(--surface-0)' }}>
        <div style={{ width:46, height:46, border:'1px solid var(--accent)', borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center', marginBottom:22 }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="1.6"><polyline points="20 6 9 17 4 12"/></svg>
        </div>
        <h3 className="akm-h3" style={{ marginBottom:12 }}>Thank you</h3>
        <p className="akm-body" style={{ maxWidth:420 }}>
          Your note is with us. We read every message ourselves and will be in touch shortly to continue the conversation.
        </p>
      </div>
    );
  }

  return (
    <form noValidate onSubmit={e => { e.preventDefault(); attemptSubmit(); }}
      style={{ display:'flex', flexDirection:'column', gap:20 }}>
      {/* honeypot — hidden from people, tempting to bots */}
      <input type="text" name="company_website" value={f.hp} onChange={set('hp')} tabIndex={-1} autoComplete="off"
        aria-hidden="true" style={{ position:'absolute', left:'-9999px', width:1, height:1, opacity:0, pointerEvents:'none' }} />

      <div className="akm-form-row" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:20 }}>
        <Field label="Name" name="name" value={f.name} onChange={set('name')} onBlur={blur('name')}
          error={touched.name && errors.name} required placeholder="Your name" autoComplete="name" />
        <Field label="Email" name="email" type="email" value={f.email} onChange={set('email')} onBlur={blur('email')}
          error={touched.email && errors.email} required placeholder="you@email.com" autoComplete="email" inputMode="email" />
      </div>
      <div className="akm-form-row" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:20 }}>
        <Field label="Phone" name="phone" type="tel" value={f.phone} onChange={set('phone')} onBlur={blur('phone')}
          error={touched.phone && errors.phone} required placeholder="(555) 555-5555" autoComplete="tel" inputMode="tel" />
        <Field label="Project type" name="project_type" value={f.kind} onChange={set('kind')} onBlur={blur('kind')}
          error={touched.kind && errors.kind} required placeholder="Choose…"
          options={['Residential (new build)','Residential (remodel)','Commercial / Institutional','Consulting','Something else']} />
      </div>
      <Field label="About the project" name="message" value={f.msg} onChange={set('msg')} onBlur={blur('msg')}
        error={touched.msg && errors.msg} required rows={4}
        placeholder="A few words on what you have in mind: location, scope, timing." />

      {submitError && (
        <span role="alert" style={{ fontFamily:'var(--font-body)', fontSize:13.5, color:'var(--danger)' }}>{submitError}</span>
      )}
      <div style={{ marginTop:6 }}>
        <Button type="submit" variant="primary" disabled={submitting} style={{ width:'100%', justifyContent:'center' }}>
          {submitting ? 'Sending…' : 'Start a conversation'}
        </Button>
      </div>
    </form>
  );
}

function Contact() {
  return (
    <section id="contact" style={{ background:'var(--surface-1)', padding:'clamp(64px,9vw,120px) 0', borderTop:'1px solid var(--line-1)' }}>
      <div style={{ maxWidth:1320, margin:'0 auto', padding:'0 clamp(20px,5vw,48px)' }}>
        <div className="akm-contact-grid" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'clamp(36px,6vw,96px)', alignItems:'start' }}>
          <Reveal>
            <Eyebrow>Get in Touch</Eyebrow>
            <h2 className="akm-h1" style={{ marginTop:18 }}>Start a conversation</h2>
            <p className="akm-body-lg" style={{ marginTop:22, maxWidth:440 }}>
              If you&rsquo;re considering a project and think we might be the right team, we&rsquo;d welcome the chance to talk it through.
            </p>
          </Reveal>
          <Reveal delay={80}><ContactForm /></Reveal>
        </div>
      </div>
    </section>
  );
}

window.Intro = Intro;
window.Services = Services;
window.Studio = Studio;
window.Contact = Contact;
