/* global React */
const { useState, useEffect, useRef } = React;
const { Icon, Imgph } = window.LYTLE_UI;

/* ============= Design CTA ============= */
function DesignCTA({ onQuote }) {
  return (
    <section className="design-cta reveal">
      <div className="wrap">
        <h2>WE'LL HANDLE THE DESIGN TOO.</h2>
        <p>No artwork? No problem. Our in-house design team will work with you to create print-ready files for whatever you're ordering.</p>
        <button className="btn ghost" onClick={onQuote}>Let's Talk</button>
      </div>
    </section>
  );
}

/* ============= Family Story ============= */
function Story() {
  return (
    <section className="story section" id="about">
      <div className="wrap">
        <div>
          <span className="eyebrow reveal">Our Story</span>
          <h2 className="reveal" style={{ marginTop: 14 }}>Family Owned.<br/>Family Run.</h2>
          <p style={{ marginTop: 22 }}>
            Since 1989, Lytle Custom Apparel has been a family-owned, family-run shop headquartered in Huntington Beach — serving businesses, teams, and organizations across Orange County and Southern California.
          </p>
          <p>
            We handle most of what we do under our own roof, which means better quality control, quicker timelines, and a team that's with you from first quote to final product. No middlemen, no runaround — just custom work done right.
          </p>
          <div className="stats" style={{ gridTemplateColumns:'repeat(3, 1fr)' }}>
            <div className="stat">
              <div className="icon" style={{ border:'none', width:64, height:64 }}><img src={'assets/about-years.png'} alt="" style={{ width:'100%', height:'100%', objectFit:'contain' }}/></div>
              <div className="label">Years In Business</div>
            </div>
            <div className="stat">
              <div className="icon" style={{ border:'none', width:64, height:64 }}><img src={'assets/about-inhouse.png'} alt="" style={{ width:'100%', height:'100%', objectFit:'contain' }}/></div>
              <div className="label">In-House Printing</div>
            </div>
            <div className="stat">
              <div className="icon" style={{ border:'none', width:64, height:64 }}><img src={'assets/about-experts.png'} alt="" style={{ width:'100%', height:'100%', objectFit:'contain' }}/></div>
              <div className="label">Expert Specialists</div>
            </div>
          </div>
        </div>
        <div className="story-image">
          <div style={{ height:'100%', backgroundImage:'url(assets/about-hb.png)', backgroundSize:'cover', backgroundPosition:'center' }}/>
          <div className="accent"/>
        </div>
      </div>
    </section>
  );
}

/* ============= Final CTA + Footer ============= */
function FinalCTA({ onQuote }) {
  return (
    <section className="final-cta reveal" id="contact">
      <div className="wrap">
        <h2>LET'S GET STARTED ON YOUR ORDER.</h2>
        <button className="btn" onClick={onQuote}>Get a Quote</button>
      </div>
    </section>
  );
}

function Footer({ onJump, onQuote }) {
  return (
    <footer className="footer">
      <div className="wrap footer-grid">
        <div>
          <div className="brand">
            <img src="assets/lytle-logo-white.png" alt="Lytle Custom Apparel" className="brand-logo brand-logo-footer" />
          </div>
          <p className="copy">Custom printing done right — for businesses, teams, and communities across Orange County and Southern California.</p>
        </div>
        <div>
          <h4>Contact</h4>
          <div className="contact-row"><Icon.Pin/><div>21572 Surveyor Cir,<br/>Huntington Beach, CA 92646</div></div>
          <div className="contact-row"><Icon.Phone/><div><a href="tel:+17149692424">(714) 969-2424</a></div></div>
          <div className="contact-row"><Icon.Mail/><div><a href="mailto:cs@lysphb.com">cs@lysphb.com</a></div></div>
        </div>
        <div>
          <h4>Quick Links</h4>
          <ul>
            <li><a href="#home" onClick={(e) => { e.preventDefault(); onJump('home'); }}>Home</a></li>
            <li><a href="#services" onClick={(e) => { e.preventDefault(); onJump('services'); }}>Services</a></li>
            <li><a href="#display" onClick={(e) => { e.preventDefault(); onJump('display'); }}>Promotional Products</a></li>
            <li><a href="team-stores.html" onClick={(e) => { e.preventDefault(); onJump('team'); }}>Team Stores</a></li>
            <li><a href="catalog.html" onClick={(e) => { e.preventDefault(); onJump('catalog'); }}>Catalog</a></li>
            <li><a href="#about" onClick={(e) => { e.preventDefault(); onJump('about'); }}>About Us</a></li>
          </ul>
        </div>
        <div>
          <h4>Hours</h4>
          <ul>
            <li>Mon–Fri · 8:30am – 5pm</li>
            <li>Sat · Closed</li>
            <li>Sun · Closed</li>
          </ul>
          <button className="btn outline-red sm" style={{ marginTop:18 }} onClick={onQuote}>Get a Quote</button>
        </div>
      </div>
      <div className="wrap footer-base">
        <span>© {new Date().getFullYear()} LYTLE CUSTOM APPAREL · ALL RIGHTS RESERVED</span>
        <span>HUNTINGTON BEACH, CA</span>
      </div>
    </footer>
  );
}

/* ============= Quote Modal ============= */
function QuoteModal({ open, onClose, prefillService }) {
  const [submitted, setSubmitted] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState(false);
  const [form, setForm] = useState({
    name:'', email:'', phone:'', company:'',
    services: [], qty:'', desc:'', turn:'1–2 weeks'
  });
  const [sections, setSections] = useState({ contact: false, services: false, project: false });

  useEffect(() => {
    if (open && prefillService) {
      setForm(f => ({ ...f, services: f.services.includes(prefillService) ? f.services : [...f.services, prefillService] }));
      setSections(s => ({ ...s, services: true }));
    }
    if (!open) {
      setTimeout(() => {
        setSubmitted(false);
        setSections({ contact: false, services: false, project: false });
      }, 300);
    }
  }, [open, prefillService]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape' && open) onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  const toggleSvc = (s) => {
    setForm(f => ({ ...f, services: f.services.includes(s) ? f.services.filter(x => x !== s) : [...f.services, s] }));
  };

  const toggleSection = (key) => setSections(s => ({ ...s, [key]: !s[key] }));

  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError(false);
    try {
      const res = await fetch('https://withflowsmith.com/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          phone: form.phone,
          company: form.company,
          services: form.services,
          qty: form.qty,
          turnaround: form.turn,
          description: form.desc,
          source: 'lytle',
        }),
      });
      if (!res.ok) throw new Error();
      setSubmitted(true);
    } catch {
      setError(true);
    } finally {
      setSending(false);
    }
  };

  const services = ['Embroidery', 'Screen Printing', 'DTF Printing', 'Laser Engraving', 'Promotional Products', 'Not Sure'];

  const contactSummary = [form.name, form.email, form.phone].filter(Boolean).join(' · ') || null;
  const servicesSummary = form.services.length > 0 ? form.services.join(', ') : null;
  const projectSummary = [form.qty, form.turn !== '1–2 weeks' ? form.turn : null].filter(Boolean).join(' · ') || null;

  return (
    <div className={"modal-backdrop" + (open ? ' open' : '')} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()} style={{ width: 'min(640px, calc(100vw - 32px))' }}>
        <button className="x" onClick={onClose} style={{ minWidth:44, minHeight:44, display:'grid', placeItems:'center' }}>×</button>
        {submitted ? (
          <div className="success">
            <div className="check">✓</div>
            <h3>Request Received.</h3>
            <p className="sub">We've received your request and will be in touch within 1–2 business days.</p>
            <button className="btn" onClick={onClose} style={{ marginTop:8 }}>Close</button>
          </div>
        ) : (
          <form onSubmit={submit}>
            <h3>LET'S GET STARTED.</h3>
            <p className="sub">Tell us about your project — we'll come back with a personalized quote and timeline.</p>

            <div className="quote-section">
              <button type="button" className={'quote-section-header' + (sections.contact ? ' open' : '')} onClick={() => toggleSection('contact')}>
                <span>Contact Info</span>
                {contactSummary && !sections.contact && <span className="quote-section-summary">{contactSummary}</span>}
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="quote-section-chev"><path d="M9 6l6 6-6 6"/></svg>
              </button>
              {sections.contact && (
                <div className="quote-section-body">
                  <div className="field"><label>Name</label><input required value={form.name} onChange={e => setForm({...form, name:e.target.value})}/></div>
                  <div className="quote-form-row" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
                    <div className="field"><label>Email</label><input required type="email" value={form.email} onChange={e => setForm({...form, email:e.target.value})}/></div>
                    <div className="field"><label>Phone</label><input required type="tel" value={form.phone} onChange={e => setForm({...form, phone:e.target.value})}/></div>
                  </div>
                  <div className="field"><label>Company <span style={{ color:'var(--muted)', fontWeight:400, textTransform:'none', letterSpacing:0 }}>(optional)</span></label><input value={form.company} onChange={e => setForm({...form, company:e.target.value})}/></div>
                </div>
              )}
            </div>

            <div className="quote-section">
              <button type="button" className={'quote-section-header' + (sections.services ? ' open' : '')} onClick={() => toggleSection('services')}>
                <span>Services Needed</span>
                {servicesSummary && !sections.services && <span className="quote-section-summary">{servicesSummary}</span>}
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="quote-section-chev"><path d="M9 6l6 6-6 6"/></svg>
              </button>
              {sections.services && (
                <div className="quote-section-body">
                  <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                    {services.map(s => (
                      <label key={s} style={{ display:'flex', alignItems:'center', gap:10, padding:'12px 14px', border:'1px solid var(--line)', cursor:'pointer', fontSize:14, fontWeight:500, color:'var(--ink-2)', textTransform:'none', letterSpacing:0, background: form.services.includes(s) ? 'rgba(255,46,46,.08)' : '#fff', borderColor: form.services.includes(s) ? 'var(--red)' : 'var(--line)' }}>
                        <input type="checkbox" checked={form.services.includes(s)} onChange={() => toggleSvc(s)} style={{ accentColor:'var(--red)', width:18, height:18 }}/>
                        {s}
                      </label>
                    ))}
                  </div>
                </div>
              )}
            </div>

            <div className="quote-section">
              <button type="button" className={'quote-section-header' + (sections.project ? ' open' : '')} onClick={() => toggleSection('project')}>
                <span>Project Details</span>
                {projectSummary && !sections.project && <span className="quote-section-summary">{projectSummary}</span>}
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="quote-section-chev"><path d="M9 6l6 6-6 6"/></svg>
              </button>
              {sections.project && (
                <div className="quote-section-body">
                  <div className="quote-form-row" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
                    <div className="field"><label>Estimated Quantity</label><input value={form.qty} onChange={e => setForm({...form, qty:e.target.value})} placeholder="e.g. 50 shirts"/></div>
                    <div className="field">
                      <label>Preferred Turnaround</label>
                      <select value={form.turn} onChange={e => setForm({...form, turn:e.target.value})}>
                        <option>ASAP</option>
                        <option>1–2 weeks</option>
                        <option>2–4 weeks</option>
                        <option>No rush</option>
                      </select>
                    </div>
                  </div>
                  <div className="field"><label>Project Description</label><textarea value={form.desc} onChange={e => setForm({...form, desc:e.target.value})} placeholder="Tell us what you're looking for — design, garment, qty, deadline. Not sure where to start? Just describe the project."/></div>
                </div>
              )}
            </div>

            {error && (
              <p style={{ color:'var(--red)', fontSize:14, marginTop:12, marginBottom:0 }}>
                Something went wrong. Please try again.
              </p>
            )}
            <div className="actions" style={{ marginTop: 20 }}>
              <button type="submit" className="btn" disabled={sending}>
                {sending ? 'Sending...' : 'Send My Quote Request'}
              </button>
              <button type="button" className="btn outline-red" onClick={onClose}>Cancel</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

/* ============= Tweaks Panel ============= */
function Tweaks({ open, onClose, state, setState }) {
  const set = (k, v) => setState(s => ({ ...s, [k]: v }));
  return (
    <div className={"tweaks" + (open ? ' open' : '')}>
      <header>
        <h4>Tweaks</h4>
        <button onClick={onClose} style={{ background:'none', border:'none', fontSize:18, color:'var(--muted)' }}>×</button>
      </header>
      <div className="body">
        <div className="row">
          <label>Hero Treatment</label>
          <div className="seg">
            {['photo', 'split', 'minimal'].map(v => (
              <button key={v} className={state.hero === v ? 'on' : ''} onClick={() => set('hero', v)}>{v}</button>
            ))}
          </div>
        </div>
        <div className="row">
          <label>Display Font</label>
          <div className="seg">
            {[['Oswald','Oswald'], ['Barlow Cond.','Barlow Condensed'], ['Anton','Anton']].map(([n, v]) => (
              <button key={v} className={state.display === v ? 'on' : ''} onClick={() => set('display', v)}>{n}</button>
            ))}
          </div>
        </div>
        <div className="row">
          <label>Density</label>
          <div className="seg">
            {['comfortable', 'tight'].map(v => (
              <button key={v} className={state.density === v ? 'on' : ''} onClick={() => set('density', v)}>{v}</button>
            ))}
          </div>
        </div>
        <div className="row">
          <label>Brand Red</label>
          <div style={{ display:'flex', gap:10, alignItems:'center' }}>
            <input type="color" value={state.red} onChange={e => set('red', e.target.value)}/>
            <code style={{ fontSize:11, color:'var(--muted)' }}>{state.red}</code>
          </div>
        </div>
      </div>
    </div>
  );
}

window.LYTLE_EXTRA = { DesignCTA, Story, FinalCTA, Footer, QuoteModal, Tweaks };

