/* AI inquiry form (gated) + Company profile download (gated) + modal shell */

const RENO_TYPES = [
  'Full villa renovation',
  'Apartment / flat renovation',
  'Kitchen only',
  'Bathroom(s) only',
  'Master bedroom only',
  'Majlis / living areas',
  'Outdoor / pool / landscape',
  'Exterior cladding & paint',
  'Other / not sure',
];

const BUDGET_BANDS = [
  'AED 50k – 150k',
  'AED 150k – 350k',
  'AED 350k – 750k',
  'AED 750k – 1.5M',
  'AED 1.5M+',
  'Not sure yet',
];

const COMMUNITIES = [
  'Emaar — Arabian Ranches', 'Emaar — Dubai Hills Estate', 'Emaar — The Springs', 'Emaar — The Meadows',
  'Emaar — Emirates Hills', 'Damac Hills', 'Damac Hills 2', 'Palm Jumeirah', 'Jumeirah Islands',
  'Jumeirah Village Circle', 'Mirdif', 'Al Barsha', 'Other',
];

/* ============ Modal shell ============ */
function Modal({ open, onClose, title, children, wide }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.body.style.overflow = 'hidden';
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(8, 8, 8, 0.85)',
      backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      padding: '6vh 4vw', overflowY: 'auto',
      animation: 'modalFade .25s ease',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: '#0F0F0E',
        border: '1px solid rgba(245,239,230,0.12)',
        width: '100%', maxWidth: wide ? 920 : 720,
        position: 'relative',
        animation: 'modalRise .35s cubic-bezier(.2,.7,.2,1)',
      }}>
        <button onClick={onClose} aria-label="Close" style={{
          position: 'absolute', top: 18, right: 18, zIndex: 1,
          width: 40, height: 40, borderRadius: '50%',
          background: 'transparent', border: '1px solid rgba(245,239,230,0.2)', color: '#F5EFE6',
          fontSize: 18, cursor: 'pointer', lineHeight: 1,
        }}>✕</button>
        <div style={{ padding: '48px 56px 56px' }} className="modal-inner">
          {title && (
            <div style={{ marginBottom: 32 }}>
              <div style={{ fontFamily: 'Manrope', fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#C9A86A', marginBottom: 12 }}>HNHUAE</div>
              <h2 style={{ fontFamily: 'Archivo Black', fontSize: 'clamp(28px, 4vw, 44px)', color: '#F5EFE6', textTransform: 'uppercase', letterSpacing: '-0.01em' }}>{title}</h2>
            </div>
          )}
          {children}
        </div>
        <style>{`
          @keyframes modalFade { from { opacity: 0; } to { opacity: 1; } }
          @keyframes modalRise { from { transform: translateY(40px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
          @media (max-width: 700px) {
            .modal-inner { padding: 32px 24px 40px !important; }
          }
        `}</style>
      </div>
    </div>
  );
}

/* ============ AI Inquiry — captures lead, then provides AI reply ============ */
function InquiryModal({ open, onClose, presetType }) {
  const [step, setStep] = useState('form'); // form -> thinking -> reply
  const [form, setForm] = useState({
    name: '', email: '', phone: '', community: '', type: '', budget: '', message: '',
  });
  const [reply, setReply] = useState('');
  const [error, setError] = useState('');

  // Reset on open / preset
  useEffect(() => {
    if (open) {
      setStep('form'); setReply(''); setError('');
      setForm(f => ({ ...f, type: presetType || f.type }));
    }
  }, [open, presetType]);

  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.email || !form.type || !form.budget) {
      setError('Please fill the required fields.');
      return;
    }
    setError('');
    setStep('thinking');

    // Save lead to localStorage for record-keeping (simulates CRM capture)
    const leads = JSON.parse(localStorage.getItem('hnhuae_leads') || '[]');
    leads.push({ ...form, ts: new Date().toISOString(), source: 'ai-inquiry' });
    localStorage.setItem('hnhuae_leads', JSON.stringify(leads));

    // Now and only now do we generate an AI response
    try {
      const prompt = `You are a senior project manager at HNHUAE Technical Services LLC, a UAE-based renovation company that completely renews much-loved villas and flats. Tone: warm, confident, concise, professional — never salesy. Never use exclamation marks. No emojis. Address the client by first name.

A new client has just submitted an inquiry. Their details:
- Name: ${form.name}
- Email: ${form.email}
- Phone: ${form.phone || 'not provided'}
- Community: ${form.community || 'not specified'}
- Type of renovation: ${form.type}
- Budget band: ${form.budget}
- Notes from client: ${form.message || '(none)'}

Write a 4-paragraph initial reply (about 140-180 words total) that:
1. Greets them by first name and acknowledges their specific renovation type and community.
2. Gives 2-3 concrete things HNHUAE typically does for that exact scope, grounded in real UAE villa/apartment renovation reality. Mention timeline ranges and that we work room-by-room with one project manager.
3. Suggests a free 30-minute site visit as the next step. If they're in a known Emaar/Damac community, mention HNHUAE has worked in similar communities.
4. Closes by saying Abid (the founder) or his team will follow up by email and WhatsApp within one business day.

Sign off: "— HNHUAE Project Office".

Output plain text only, no markdown headers, no bullet lists. Use clean paragraph breaks (double newline).`;

      const text = await window.claude.complete(prompt);
      setReply(text);
      setStep('reply');
    } catch (err) {
      setReply(`Hi ${form.name.split(' ')[0]},\n\nThank you for the details. We've logged your inquiry for a ${form.type.toLowerCase()} ${form.community ? 'in ' + form.community : 'in the UAE'}, with a budget band of ${form.budget}.\n\nA member of the HNHUAE project office will reach out within one business day to schedule a free site visit. In the meantime, feel free to send any photos of the existing space to abidabizher@gmail.com — they'll go straight into your project file.\n\n— HNHUAE Project Office`);
      setStep('reply');
    }
  };

  return (
    <Modal open={open} onClose={onClose} title="Start an Inquiry">
      {step === 'form' && (
        <>
          <p style={{ marginTop: -16, marginBottom: 36, fontFamily: 'Manrope', fontSize: 16, lineHeight: 1.55, color: 'rgba(245,239,230,0.7)' }}>
            Tell us about your space. Our AI assistant will give an immediate first response, then a senior project manager follows up within one business day.
          </p>
          <form onSubmit={submit} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }} className="form-grid">
            <Field name="name" label="Full name" value={form.name} onChange={update('name')} required />
            <Field name="email" label="Email" type="email" value={form.email} onChange={update('email')} required />
            <Field name="phone" label="Phone / WhatsApp" type="tel" value={form.phone} onChange={update('phone')} placeholder="+971…" />
            <Field name="community" label="Community" value={form.community} onChange={update('community')} options={COMMUNITIES} />
            <Field name="type" label="Type of renovation" value={form.type} onChange={update('type')} options={RENO_TYPES} required />
            <Field name="budget" label="Budget band (AED)" value={form.budget} onChange={update('budget')} options={BUDGET_BANDS} required />
            <div style={{ gridColumn: 'span 2' }}>
              <Field name="message" label="Anything we should know?" value={form.message} onChange={update('message')} placeholder="Bedrooms? Square footage? Move-in target?" rows={3} />
            </div>
            <div style={{ gridColumn: 'span 2', marginTop: 8 }}>
              {error && <div style={{ color: '#FFCB45', fontFamily: 'Manrope', fontSize: 14, marginBottom: 14 }}>{error}</div>}
              <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
                <Btn type="submit" variant="primary">Send & Get AI Reply →</Btn>
                <span style={{ fontFamily: 'Manrope', fontSize: 12, color: '#8B847A', letterSpacing: '0.06em' }}>
                  We respond by email and WhatsApp within 1 business day.
                </span>
              </div>
            </div>
          </form>
          <style>{`
            @media (max-width: 700px) {
              .form-grid { grid-template-columns: 1fr !important; }
              .form-grid > div[style*="span 2"] { grid-column: span 1 !important; }
            }
          `}</style>
        </>
      )}

      {step === 'thinking' && (
        <div style={{ padding: '60px 0', textAlign: 'center' }}>
          <div className="thinking-dots" style={{ display: 'inline-flex', gap: 8 }}>
            <span></span><span></span><span></span>
          </div>
          <p style={{ marginTop: 24, fontFamily: 'Instrument Serif, serif', fontStyle: 'italic', fontSize: 22, color: '#C9A86A' }}>
            Reading your details…
          </p>
          <p style={{ marginTop: 8, fontFamily: 'Manrope', fontSize: 13, color: '#8B847A', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
            Inquiry saved · drafting initial reply
          </p>
          <style>{`
            .thinking-dots span {
              width: 10px; height: 10px; border-radius: 50%; background: #F5B82E;
              animation: dotBlink 1.4s infinite ease-in-out;
            }
            .thinking-dots span:nth-child(2) { animation-delay: 0.2s; }
            .thinking-dots span:nth-child(3) { animation-delay: 0.4s; }
            @keyframes dotBlink { 0%, 80%, 100% { opacity: .25; transform: scale(0.85); } 40% { opacity: 1; transform: scale(1); } }
          `}</style>
        </div>
      )}

      {step === 'reply' && (
        <div>
          <div style={{
            padding: '12px 16px', marginBottom: 28, marginTop: -8,
            background: 'rgba(245,184,46,0.1)', border: '1px solid rgba(245,184,46,0.3)',
            display: 'flex', gap: 12, alignItems: 'center',
          }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#F5B82E' }}></span>
            <span style={{ fontFamily: 'Manrope', fontSize: 13, color: '#F5EFE6' }}>
              Inquiry received from <strong>{form.name}</strong> · sent to <strong>{form.email}</strong>
            </span>
          </div>
          <div style={{
            padding: '32px 36px', background: '#141414', border: '1px solid rgba(245,239,230,0.08)',
            position: 'relative',
          }}>
            <div style={{ fontFamily: 'Manrope', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#C9A86A', marginBottom: 18 }}>
              ── First reply from HNHUAE
            </div>
            <div style={{
              fontFamily: 'Manrope', fontSize: 17, lineHeight: 1.65, color: 'rgba(245,239,230,0.92)',
              whiteSpace: 'pre-wrap',
            }}>
              {reply}
            </div>
          </div>
          <div style={{ marginTop: 28, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <Btn variant="primary" href="https://wa.me/971555455375" rel="noopener" target="_blank">Continue on WhatsApp →</Btn>
            <Btn variant="ghost" onClick={onClose}>Close</Btn>
          </div>
        </div>
      )}
    </Modal>
  );
}

/* ============ Download Profile — gated by simple lead capture ============ */
function DownloadModal({ open, onClose }) {
  const [step, setStep] = useState('form');
  const [form, setForm] = useState({ name: '', email: '', phone: '', community: '', type: '' });
  const [error, setError] = useState('');

  useEffect(() => {
    if (open) { setStep('form'); setError(''); }
  }, [open]);

  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.email) { setError('Name and email are required.'); return; }
    setError('');

    const leads = JSON.parse(localStorage.getItem('hnhuae_leads') || '[]');
    leads.push({ ...form, ts: new Date().toISOString(), source: 'profile-download' });
    localStorage.setItem('hnhuae_leads', JSON.stringify(leads));

    // Generate the company profile as a printable HTML, open in new tab for save-as-PDF
    const html = generateProfileHTML(form);
    const blob = new Blob([html], { type: 'text/html' });
    const url = URL.createObjectURL(blob);
    // Trigger download
    const a = document.createElement('a');
    a.href = url;
    a.download = `HNHUAE-Company-Profile-${form.name.split(' ')[0]}.html`;
    a.click();
    setTimeout(() => URL.revokeObjectURL(url), 5000);

    setStep('done');
  };

  return (
    <Modal open={open} onClose={onClose} title="Download Company Profile">
      {step === 'form' && (
        <>
          <p style={{ marginTop: -16, marginBottom: 36, fontFamily: 'Manrope', fontSize: 16, lineHeight: 1.55, color: 'rgba(245,239,230,0.7)' }}>
            A 12-page profile with services, process, communities served, and project gallery. Quick details first — your file downloads instantly.
          </p>
          <form onSubmit={submit} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }} className="form-grid">
            <Field name="name" label="Full name" value={form.name} onChange={update('name')} required />
            <Field name="email" label="Email" type="email" value={form.email} onChange={update('email')} required />
            <Field name="phone" label="Phone / WhatsApp" value={form.phone} onChange={update('phone')} placeholder="+971…" />
            <Field name="community" label="Community" value={form.community} onChange={update('community')} options={COMMUNITIES} />
            <div style={{ gridColumn: 'span 2' }}>
              <Field name="type" label="Type of renovation (optional)" value={form.type} onChange={update('type')} options={RENO_TYPES} />
            </div>
            <div style={{ gridColumn: 'span 2', marginTop: 8 }}>
              {error && <div style={{ color: '#FFCB45', fontFamily: 'Manrope', fontSize: 14, marginBottom: 14 }}>{error}</div>}
              <Btn type="submit" variant="primary">Download Profile (.html) ↓</Btn>
              <div style={{ marginTop: 14, fontFamily: 'Manrope', fontSize: 12, color: '#8B847A' }}>
                Open the file in your browser, then File → Print → Save as PDF for the print-ready version.
              </div>
            </div>
          </form>
        </>
      )}
      {step === 'done' && (
        <div style={{ padding: '32px 0' }}>
          <div style={{ fontFamily: 'Instrument Serif, serif', fontStyle: 'italic', fontSize: 32, color: '#F5B82E', marginBottom: 14 }}>Thank you, {form.name.split(' ')[0]}.</div>
          <p style={{ fontFamily: 'Manrope', fontSize: 17, lineHeight: 1.6, color: 'rgba(245,239,230,0.8)', maxWidth: 540, marginBottom: 28 }}>
            Your company profile has been downloaded. We've also added you to our records — Abid or a senior PM will reach out shortly to introduce HNHUAE personally.
          </p>
          <Btn variant="ghost" onClick={onClose}>Close</Btn>
        </div>
      )}
    </Modal>
  );
}

/* ============ Generate the company profile HTML (printable) ============ */
function generateProfileHTML(form) {
  const date = new Date().toLocaleDateString('en-GB', { day: '2-digit', month: 'long', year: 'numeric' });
  return `<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>HNHUAE — Company Profile</title>
<link href="https://fonts.googleapis.com/css2?family=Archivo+Black&family=Manrope:wght@300;400;500;600;700&family=Instrument+Serif:ital@0;1&display=swap" rel="stylesheet">
<style>
@page { size: A4; margin: 18mm; }
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Manrope', sans-serif; color: #1A1A1A; background: #F5EFE6; line-height: 1.5; }
.page { min-height: 100vh; padding: 60px 80px; page-break-after: always; }
.page:last-child { page-break-after: auto; }
h1, h2, h3 { font-family: 'Archivo Black', sans-serif; text-transform: uppercase; letter-spacing: -0.01em; line-height: 0.95; }
.serif { font-family: 'Instrument Serif', serif; font-style: italic; font-weight: 400; text-transform: none; letter-spacing: 0; }
.hl { background: #F5B82E; color: #0A0A0A; padding: 0.05em 0.18em; }
.eyebrow { font-size: 11px; letter-spacing: 0.22em; text-transform: uppercase; color: #8B7A4F; margin-bottom: 18px; }
.cover { background: #0A0A0A; color: #F5EFE6; min-height: 100vh; display: flex; flex-direction: column; justify-content: space-between; padding: 60px; }
.cover h1 { font-size: 88px; }
.cover .mark { font-size: 22px; letter-spacing: 0.08em; }
.cover .mark span { color: #F5B82E; }
table { width: 100%; border-collapse: collapse; margin-top: 16px; }
td { padding: 14px 0; border-bottom: 1px solid rgba(0,0,0,0.1); font-size: 14px; }
td:first-child { font-weight: 600; color: #8B7A4F; width: 40%; text-transform: uppercase; letter-spacing: 0.08em; font-size: 11px; }
ul.rooms { list-style: none; column-count: 2; column-gap: 40px; margin-top: 18px; }
ul.rooms li { padding: 14px 0; border-top: 1px solid rgba(0,0,0,0.1); break-inside: avoid; font-size: 15px; }
ul.rooms li small { display: block; color: #8B7A4F; font-size: 12px; margin-top: 4px; }
.steps { display: grid; grid-template-columns: repeat(5, 1fr); gap: 0; margin-top: 24px; }
.steps > div { padding: 18px 14px 18px 0; border-top: 2px solid #1A1A1A; border-right: 1px solid rgba(0,0,0,0.1); }
.steps > div:last-child { border-right: none; }
.steps .num { font-family: 'Instrument Serif', serif; font-style: italic; font-size: 24px; color: #C9A86A; }
.steps h4 { font-size: 16px; margin: 8px 0 6px; }
.steps p { font-size: 12px; color: #555; }
.communities { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 16px; }
.communities span { padding: 8px 14px; background: #1A1A1A; color: #F5EFE6; font-size: 12px; letter-spacing: 0.06em; }
.print-hint { position: fixed; top: 12px; right: 12px; background: #0A0A0A; color: #F5B82E; padding: 10px 16px; font-size: 12px; }
@media print { .print-hint { display: none; } body { background: #fff; } .page { padding: 0; } }
</style></head>
<body>
<div class="print-hint">Tip: File → Print → Save as PDF</div>

<section class="page cover">
  <div class="mark">HN<span>·</span>HUAE</div>
  <div>
    <div class="eyebrow" style="color:#C9A86A">Company Profile · ${date}</div>
    <h1>We give <span class="hl">much-loved villas</span><br/>a new chapter.</h1>
    <p class="serif" style="font-size:28px;color:#C9A86A;margin-top:24px;">Renewing much-loved villas and flats across the UAE.</p>
  </div>
  <div style="font-size:12px; letter-spacing: 0.08em; color: rgba(245,239,230,0.6);">
    Prepared for ${form.name}${form.community ? ' · ' + form.community : ''} · ${date}
  </div>
</section>

<section class="page">
  <div class="eyebrow">01 · About</div>
  <h2 style="font-size:48px;max-width:14ch">Is your home ready for a <span class="hl">new chapter</span>?</h2>
  <p style="margin-top:24px;font-size:16px;max-width:60ch">HNHUAE Technical Services LLC is a UAE-based renovation and refurbishment company. We specialise in taking much-loved villas and flats and giving them a complete second life — managed end-to-end by one team, with one project manager and one fixed price.</p>
  <p style="margin-top:14px;font-size:16px;max-width:60ch">Founded by Abid Abizher Mohammed, HNHUAE has refurbished over 200 homes across Emaar, Damac, Nakheel, and freehold communities. Civil, MEP, joinery, finishing, smart-home, and landscaping are all in-house — never sub-contracted to strangers.</p>

  <table>
    <tr><td>Founder</td><td>Abid Abizher Mohammed</td></tr>
    <tr><td>Established</td><td>2014, Dubai UAE</td></tr>
    <tr><td>Service Area</td><td>All seven emirates · primarily Dubai, Abu Dhabi, Sharjah</td></tr>
    <tr><td>Specialty</td><td>Complete villa &amp; apartment renovation</td></tr>
    <tr><td>Trades in-house</td><td>Civil · MEP · Joinery · Stone · Paint · Smart-home · Landscape</td></tr>
    <tr><td>Warranty</td><td>12 months workmanship · plus material/manufacturer cover</td></tr>
  </table>
</section>

<section class="page">
  <div class="eyebrow">02 · Rooms we renovate</div>
  <h2 style="font-size:48px">Every room. <span class="hl">One team.</span></h2>
  <ul class="rooms">
    ${ROOMS.map(r => `<li><strong>${String(r.n).padStart(2,'0')} · ${r.title}</strong><small>${r.notes}</small></li>`).join('')}
  </ul>
</section>

<section class="page">
  <div class="eyebrow">03 · Process</div>
  <h2 style="font-size:48px">Managed the <span class="hl">right way.</span></h2>
  <div class="steps">
    <div><div class="num">01</div><h4>Discovery</h4><p>Site visit, listening, measuring, photographing.</p></div>
    <div><div class="num">02</div><h4>Design</h4><p>Mood, materials, drawings, fixed price you approve.</p></div>
    <div><div class="num">03</div><h4>Build</h4><p>Civil, MEP, finishing under one site manager.</p></div>
    <div><div class="num">04</div><h4>Finish</h4><p>Stone, paint, joinery, lighting, the small things.</p></div>
    <div><div class="num">05</div><h4>Handover</h4><p>Walkthrough, snag list, 12-month warranty.</p></div>
  </div>
</section>

<section class="page">
  <div class="eyebrow">04 · Communities served</div>
  <h2 style="font-size:48px">Trusted across <span class="hl">Dubai's best</span> addresses.</h2>
  <p style="margin-top:18px;font-size:15px;max-width:60ch">Whether the keys came from Emaar handover, a Damac off-plan completion, or a freehold flat in Mirdif — we know the community by-laws, the NOC processes, and the build details by heart.</p>
  <div class="communities">
    ${['Emaar — Arabian Ranches','Emaar — Dubai Hills Estate','Emaar — The Springs','Emaar — The Meadows','Emaar — Emirates Hills','Damac Hills','Damac Hills 2','Palm Jumeirah','Jumeirah Islands','Jumeirah Village Circle','Mirdif','Al Barsha','Jumeirah Park','Mudon','Town Square','Reem','The Lakes'].map(c => `<span>${c}</span>`).join('')}
  </div>
</section>

<section class="page">
  <div class="eyebrow">05 · Contact</div>
  <h2 style="font-size:64px">Ready to <span class="hl">begin?</span></h2>
  <table style="margin-top:32px;">
    <tr><td>Founder</td><td>Abid Abizher Mohammed</td></tr>
    <tr><td>Phone / WhatsApp</td><td>+971 55 545 5375</td></tr>
    <tr><td>Email</td><td>abidabizher@gmail.com</td></tr>
    <tr><td>Instagram</td><td>@thehnhuae</td></tr>
    <tr><td>Service Area</td><td>UAE (all seven emirates)</td></tr>
  </table>
  <p style="margin-top:48px;font-family:'Instrument Serif',serif;font-style:italic;font-size:22px;color:#C9A86A;max-width:60ch">"Every successful renovation begins with a real conversation about what the home needs to become."</p>
  <p style="margin-top:8px;font-size:11px;letter-spacing:0.18em;text-transform:uppercase;color:#8B7A4F">— Abid Abizher Mohammed · Founder</p>
</section>

</body></html>`;
}

Object.assign(window, { InquiryModal, DownloadModal, RENO_TYPES, BUDGET_BANDS, COMMUNITIES });
