// Resolves an asset through the bundler's inlined resource map in the
// standalone build, falling back to the relative path in dev. Declared locally
// because Babel scripts don't share top-level scope.
const FRES = (id, path) => (typeof window !== 'undefined' && window.__resources && window.__resources[id]) || path;

// Quote flow + footer + WhatsApp widget
const PRODUCT_LIST = ['Peaches','Nectarines','Apricots','Cherries','Plums','Oranges','Lemons','Mandarins','Strawberries','Blueberries','Grapes','Melons','Kiwis','Tomatoes','Peppers','Courgettes','Cucumbers','Lettuce','Broccoli','Asparagus','Onions','Mixed pallet'];

function QuoteFlow(){
  const [data, setData] = useState({ name:'', company:'', email:'', phone:'', notes:'' });
  const [submitted, setSubmitted] = useState(false);
  const update = (k,v) => setData(d => ({...d, [k]:v}));
  const canSubmit = data.name.trim() && data.email.trim() && data.company.trim();

  return (
    <section id="quote" className="section-pad" style={{background:'var(--forest-deep)', color:'var(--cream)'}}>
      <div className="container">
        <div style={{display:'grid', gridTemplateColumns:'1fr 1.5fr', gap:80}} className="q-grid">
          <div>
            <div className="eyebrow" style={{marginBottom:20, marginLeft:0, marginRight:0}}>Contact</div>
            <h2 className="h-1" style={{margin:'0 0 24px', color:'var(--cream)'}}>Tell us what <em>you need.</em></h2>
            <p style={{color:'rgba(244,239,226,0.7)', fontSize:16, lineHeight:1.6, marginBottom:32, maxWidth:'40ch'}}>
              Send a quick message, or book a 15-minute intro call directly in our diary.
            </p>

            <div style={{display:'flex', flexDirection:'column', gap:12, paddingTop:24, borderTop:'1px solid rgba(255,255,255,0.12)'}}>
              <a href="https://calendly.com/plengland-sales/30min" target="_blank" rel="noopener noreferrer" style={{display:'flex', alignItems:'center', gap:14, padding:'14px 18px', background:'#fff', color:'var(--ink)', borderRadius:999, fontWeight:500, boxShadow:'0 1px 2px rgba(0,0,0,0.04), 0 4px 12px rgba(0,0,0,0.06)'}}>
                <Icon.Pin size={18}/>
                <div style={{display:'flex', flexDirection:'column', lineHeight:1.2}}>
                  <span style={{fontSize:10.5, opacity:0.55, fontWeight:500, letterSpacing:'0.06em'}}>30 min</span>
                  <span style={{fontSize:14}}>Book a call</span>
                </div>
              </a>
              <a href="http://wa.me/+447808034216" style={{display:'flex', alignItems:'center', gap:14, padding:'14px 18px', background:'#fff', color:'var(--ink)', borderRadius:999, fontWeight:500, boxShadow:'0 1px 2px rgba(0,0,0,0.04), 0 4px 12px rgba(0,0,0,0.06)'}}>
                <Icon.Whatsapp size={18}/>
                <span style={{fontSize:14}}>Message us on WhatsApp</span>
              </a>
              <a href="mailto:sales@plengland.co.uk" style={{display:'flex', gap:12, alignItems:'center', color:'rgba(244,239,226,0.85)', fontSize:14, padding:'6px 4px'}}>
                <Icon.Mail size={16}/> sales@plengland.co.uk
              </a>
            </div>
          </div>

          <div style={{
            background:'rgba(255,255,255,0.04)', border:'1px solid rgba(255,255,255,0.1)',
            borderRadius:'var(--radius-lg)', padding:'36px 40px'
          }}>
            {submitted ? (
              <div style={{padding:'40px 0', textAlign:'center'}}>
                <div style={{
                  width:64, height:64, borderRadius:'50%', background:'var(--leaf)',
                  display:'inline-flex', alignItems:'center', justifyContent:'center', marginBottom:24, color:'#fff'
                }}>
                  <Icon.Check size={28}/>
                </div>
                <h3 className="h-2" style={{margin:'0 0 12px', color:'var(--cream)'}}>Request <em>received.</em></h3>
                <p style={{color:'rgba(244,239,226,0.7)', maxWidth:'42ch', margin:'0 auto'}}>
                  Thanks {data.name?.split(' ')[0] || 'there'}, we've logged your enquiry. A sales rep will be in touch within one business day at {data.email}.
                </p>
                <button onClick={()=>{ setSubmitted(false); setData({ name:'', company:'', email:'', phone:'', notes:'' }); }} className="btn btn-ghost" style={{marginTop:24, color:'var(--cream)', borderColor:'rgba(255,255,255,0.2)'}}>Submit another</button>
              </div>
            ) : (
              <div style={{display:'flex', flexDirection:'column', gap:20}}>
                <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:16}}>
                  <div>
                    <label style={{color:'rgba(244,239,226,0.6)'}}>Full name</label>
                    <input value={data.name} onChange={e=>update('name', e.target.value)} style={{background:'rgba(255,255,255,0.04)', borderColor:'rgba(255,255,255,0.15)', color:'var(--cream)'}}/>
                  </div>
                  <div>
                    <label style={{color:'rgba(244,239,226,0.6)'}}>Company</label>
                    <input value={data.company} onChange={e=>update('company', e.target.value)} style={{background:'rgba(255,255,255,0.04)', borderColor:'rgba(255,255,255,0.15)', color:'var(--cream)'}}/>
                  </div>
                </div>
                <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:16}}>
                  <div>
                    <label style={{color:'rgba(244,239,226,0.6)'}}>Email</label>
                    <input type="email" value={data.email} onChange={e=>update('email', e.target.value)} style={{background:'rgba(255,255,255,0.04)', borderColor:'rgba(255,255,255,0.15)', color:'var(--cream)'}}/>
                  </div>
                  <div>
                    <label style={{color:'rgba(244,239,226,0.6)'}}>Phone (optional)</label>
                    <input value={data.phone} onChange={e=>update('phone', e.target.value)} style={{background:'rgba(255,255,255,0.04)', borderColor:'rgba(255,255,255,0.15)', color:'var(--cream)'}}/>
                  </div>
                </div>
                <div>
                  <label style={{color:'rgba(244,239,226,0.6)'}}>What are you looking to source? (optional)</label>
                  <textarea rows={3} value={data.notes} onChange={e=>update('notes', e.target.value)} placeholder="Products, quantities, destination…" style={{background:'rgba(255,255,255,0.04)', borderColor:'rgba(255,255,255,0.15)', color:'var(--cream)', resize:'vertical'}}/>
                </div>

                <div style={{display:'flex', justifyContent:'flex-end', marginTop:8, paddingTop:24, borderTop:'1px solid rgba(255,255,255,0.1)'}}>
                  <button onClick={async ()=>{
                    if (!canSubmit) return;
                    // Submit via FormSubmit.co AJAX endpoint — sends to sales@plengland.co.uk.
                    // First-ever submission triggers a one-time confirmation email; all subsequent
                    // ones land directly in the inbox. No backend needed.
                    try {
                      await fetch('https://formsubmit.co/ajax/sales@plengland.co.uk', {
                        method: 'POST',
                        headers: { 'Content-Type':'application/json', 'Accept':'application/json' },
                        body: JSON.stringify({
                          _subject: `New enquiry — ${data.name || 'Website'} (${data.company || 'no company'})`,
                          _captcha: 'false',
                          _template: 'table',
                          Name: data.name,
                          Company: data.company,
                          Email: data.email,
                          Phone: data.phone,
                          Notes: data.notes,
                          Source: 'plengland.co.uk — quote form',
                        }),
                      });
                    } catch(_e) { /* still show thanks; user gets fallback via mailto */ }
                    setSubmitted(true);
                  }} disabled={!canSubmit} className="btn btn-primary" style={{opacity: canSubmit?1:0.5}}>
                    Submit request <Icon.Check size={14}/>
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) { .q-grid { grid-template-columns: 1fr !important; gap: 40px !important; } }
      `}</style>
    </section>
  );
}

function Footer(){
  return (
    <footer style={{background:'var(--forest-deep)', color:'rgba(244,239,226,0.7)', padding:'80px 0 32px'}}>
      <div className="container">
        <div style={{display:'grid', gridTemplateColumns:'1.6fr 1fr 1fr 1.2fr', gap:48, marginBottom:64}} className="foot-grid">
          <div>
            <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:18}}>
              <span style={{
                width:46, height:46, borderRadius:'50%',
                background:'var(--cream)',
                border:`1.5px solid var(--tomato)`,
                position:'relative', flexShrink:0,
                display:'grid', placeItems:'center'
              }}>
                <span style={{
                  position:'absolute', inset:'10%', borderRadius:'50%',
                  border:'1.2px solid var(--tomato)'
                }}/>
                <svg width="28" height="30" viewBox="0 0 60 64" aria-hidden style={{position:'relative'}}>
                  <path d="M30 22 C 30 14, 30 10, 30 6" stroke="#1A2418" strokeWidth="1.6" strokeLinecap="round" fill="none"/>
                  <path d="M30 12 C 36 8, 44 8, 46 14 C 42 18, 34 18, 30 12 Z" fill="#1F3D2E"/>
                  <ellipse cx="30" cy="40" rx="18" ry="19" fill="#D63B27"/>
                  <path d="M30 23 C 28 36, 28 52, 30 58" stroke="#1A2418" strokeOpacity="0.22" strokeWidth="1.4" fill="none"/>
                  <ellipse cx="22" cy="32" rx="3.6" ry="6" fill="#FAF6EC" opacity="0.34" transform="rotate(-22 22 32)"/>
                </svg>
              </span>
              <div style={{display:'flex', flexDirection:'column', lineHeight:1}}>
                <span style={{fontFamily:"'NormalAmp', 'Archivo', 'Arial Black', sans-serif", fontWeight:800, color:'var(--tomato)', fontSize:20, letterSpacing:'-0.02em'}}>P&amp;L England</span>
                <span style={{fontSize:9.5, fontWeight:600, color:'rgba(244,239,226,0.5)', letterSpacing:'0.32em', textTransform:'uppercase', marginTop:5}}>Simply Fresh</span>
              </div>
            </div>
            <p style={{margin:'0 0 20px', maxWidth:'34ch', fontSize:14.5, lineHeight:1.6}}>
              Delivering quality fresh produce, sourced from Rungis International Market, Paris, to Africa, the Middle East, the USA and beyond.
            </p>
            <div style={{display:'flex', flexDirection:'column', gap:6, marginBottom:20, fontSize:13.5, lineHeight:1.5}}>
              <span><strong style={{fontWeight:600}}>London</strong> — 3rd Floor, 86–90 Paul Street, London EC2A 4NE</span>
              <span><strong style={{fontWeight:600}}>France</strong> — 121 Rue de Chateaurenard, 94572 Rungis Cedex, France</span>
              <span style={{opacity:0.7}}>FDA-registered facility</span>
            </div>
            <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
              <a href="http://wa.me/+447808034216" className="btn" style={{padding:'10px 14px', fontSize:13, background:'rgba(255,255,255,0.06)', color:'var(--cream)', border:'1px solid rgba(255,255,255,0.1)'}}>
                <Icon.Whatsapp size={14}/> WhatsApp
              </a>
              <a href="mailto:sales@plengland.co.uk" className="btn" style={{padding:'10px 14px', fontSize:13, background:'rgba(255,255,255,0.06)', color:'var(--cream)', border:'1px solid rgba(255,255,255,0.1)'}}>
                <Icon.Mail size={14}/> Email
              </a>
              <a href="https://www.instagram.com/plenglandltd/" target="_blank" rel="noopener noreferrer" className="btn" style={{padding:'10px 14px', fontSize:13, background:'rgba(255,255,255,0.06)', color:'var(--cream)', border:'1px solid rgba(255,255,255,0.1)'}}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="2" y="2" width="20" height="20" rx="5" ry="5"/>
                  <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/>
                  <line x1="17.5" y1="6.5" x2="17.5" y2="6.5"/>
                </svg>
                Instagram
              </a>
            </div>
          </div>

          {[
            ['Quick Links', [['About','#about'],['Produce','#produce'],['Pricing','#pricing'],['Routes','#routes'],['Contact','#quote']]],
            ['Services', [['Get Pricing','#pricing'],['Documentation','#documentation'],['Sourcing','#about'],['FAQ','#faq']]],
          ].map(([title, links])=>(
            <div key={title}>
              <div style={{fontSize:12, fontWeight:600, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--cream)', marginBottom:18}}>{title}</div>
              <div style={{display:'flex', flexDirection:'column', gap:10}}>
                {links.map(([l,h])=>(
                  <a key={l} href={h} style={{fontSize:14, color:'rgba(244,239,226,0.7)', transition:'color 0.15s'}}
                     onMouseEnter={e=>e.currentTarget.style.color='var(--cream)'}
                     onMouseLeave={e=>e.currentTarget.style.color='rgba(244,239,226,0.7)'}>{l}</a>
                ))}
              </div>
            </div>
          ))}

          <div>
            <div style={{fontSize:12, fontWeight:600, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--cream)', marginBottom:18}}>Contact</div>
            <div style={{display:'flex', flexDirection:'column', gap:10, fontSize:14}}>
              <a href="mailto:sales@plengland.co.uk">sales@plengland.co.uk</a>
              <a href="http://wa.me/+447808034216">+44 7808 034216</a>
            </div>
          </div>
        </div>

        {/* Payment methods — official Stripe badge and card-brand artwork.
            The badge uses Stripe's white variant for dark backgrounds; the card
            logos sit on a white chip because their brand marks are dark and
            are specified for light backgrounds. */}
        <div style={{
          padding:'24px 0', borderTop:'1px solid rgba(255,255,255,0.08)',
          display:'flex', alignItems:'center', gap:16, flexWrap:'wrap'
        }}>
          <img src={FRES('poweredByStripe','assets/powered-by-stripe-white.svg')} alt="Powered by Stripe" width="132" height="30" style={{display:'block', flexShrink:0}}/>
          <span style={{
            display:'inline-flex', alignItems:'center',
            background:'#fff', borderRadius:6, padding:'6px 10px', flexShrink:0
          }}>
            <img src={FRES('cardLogos','assets/card-logos.svg')} alt="American Express, Mastercard and Visa accepted" width="123" height="40" style={{display:'block'}}/>
          </span>
          <span style={{fontSize:12.5, color:'rgba(244,239,226,0.5)'}}>Bank transfer also accepted, in your local currency</span>
        </div>

        {/* Compliance / registration row */}
        <div style={{
          padding:'24px 0', borderTop:'1px solid rgba(255,255,255,0.08)',
          display:'flex', flexDirection:'column', gap:16
        }}>
          <div style={{display:'flex', gap:24, flexWrap:'wrap', fontSize:13.5}}>
            <a href="/customerportal/" style={{color:'rgba(244,239,226,0.75)'}}>Customer Portal</a>
            <a href="/vendorportal/" style={{color:'rgba(244,239,226,0.75)'}}>Vendor Portal</a>
            <a href="/trackyourcargo/" style={{color:'rgba(244,239,226,0.75)'}}>Track Your Cargo</a>
            <a href="Terms & Conditions.html" style={{color:'rgba(244,239,226,0.75)'}}>Terms &amp; Conditions</a>
            <a href="Privacy Policy.html" style={{color:'rgba(244,239,226,0.75)'}}>Privacy Policy</a>
            <a href="Cookie Policy.html" style={{color:'rgba(244,239,226,0.75)'}}>Cookie Policy</a>
          </div>
          <div style={{
            display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:16,
            fontSize:12.5, color:'rgba(244,239,226,0.5)'
          }}>
            <div>© 2026 P&L England Ltd. All rights reserved.</div>
            <div style={{display:'flex', gap:24, flexWrap:'wrap'}}>
              <span>Companies House <strong style={{color:'rgba(244,239,226,0.85)'}}>11684967</strong></span>
              <span>VAT <strong style={{color:'rgba(244,239,226,0.85)'}}>GB 494 0985 47</strong></span>
              <span>Registered in England & Wales</span>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) { .foot-grid { grid-template-columns: 1fr 1fr !important; } }
        @media (max-width: 560px) { .foot-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </footer>
  );
}

function WhatsappFab(){
  const [open, setOpen] = useState(false);
  const [autoShown, setAutoShown] = useState(false);
  const [name, setName] = useState('');

  // Greet automatically a few seconds after landing, once per session.
  useEffect(() => {
    if (sessionStorage.getItem('pl-chat-greeted')) return;
    const t = setTimeout(() => {
      setOpen(true);
      setAutoShown(true);
      sessionStorage.setItem('pl-chat-greeted', '1');
    }, 2500);
    return () => clearTimeout(t);
  }, []);

  const waHref = name.trim()
    ? `http://wa.me/+447808034216?text=${encodeURIComponent(`Hi, I'm ${name.trim()} — `)}`
    : 'http://wa.me/+447808034216';

  return (
    <div style={{position:'fixed', bottom:24, right:24, zIndex:100, display:'flex', flexDirection:'column', alignItems:'flex-end', gap:12}}>
      {open && (
        <div className="wa-fab-panel" style={{
          background:'var(--paper)', border:'1px solid var(--line)',
          borderRadius:'var(--radius-lg)', padding:0, overflow:'hidden',
          width:300, boxShadow:'0 20px 50px -20px rgba(0,0,0,0.25)'
        }}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'14px 16px', borderBottom:'1px solid var(--line)', background:'var(--paper-2)'}}>
            <span style={{display:'flex', alignItems:'center', gap:8}}>
              <Logo size={30} iconOnly={true} badge={true}/>
              <span style={{fontFamily:'var(--sans)', fontSize:15, fontWeight:600}}>P&L England</span>
            </span>
            <span style={{display:'flex', alignItems:'center', gap:14}}>
              <button onClick={()=>setOpen(false)} aria-label="Close chat" style={{color:'var(--ink-2)'}}><Icon.X size={16}/></button>
            </span>
          </div>
          <div style={{padding:16, display:'flex', flexDirection:'column', gap:10}}>
            <div style={{background:'var(--paper-2)', borderRadius:'var(--radius)', padding:'10px 14px', fontSize:13.5, lineHeight:1.5, color:'var(--ink)'}}>
              Have a question about P&L England? I'm happy to help.
            </div>
            <div style={{background:'var(--paper-2)', borderRadius:'var(--radius)', padding:'10px 14px', fontSize:13.5, lineHeight:1.5, color:'var(--ink)'}}>
              Before we dive in, may we have your name?
            </div>
            <input value={name} onChange={e=>setName(e.target.value)} placeholder="Your name"
              style={{fontSize:13.5, padding:'10px 12px'}}
              onKeyDown={e=>{ if(e.key==='Enter' && name.trim()) window.open(waHref, '_blank'); }}/>
            <a href={waHref} target="_blank" rel="noopener noreferrer" className="btn btn-whatsapp" style={{width:'100%', justifyContent:'center'}}>
              <Icon.Whatsapp size={16}/> Continue on WhatsApp
            </a>
          </div>
        </div>
      )}
      <button className="wa-fab" onClick={()=>setOpen(!open)} aria-label="Open chat" style={{
        width:56, height:56, borderRadius:'50%', background:'var(--ink)', color:'var(--cream)',
        display:'flex', alignItems:'center', justifyContent:'center',
        boxShadow:'0 12px 32px -8px rgba(0,0,0,0.4)', cursor:'pointer'
      }}>
        {open ? <Icon.X size={22}/> : <Icon.Chat size={24}/>}
      </button>
    </div>
  );
}

Object.assign(window, { QuoteFlow, Footer, WhatsappFab });
