/* === ROAR shared components === */

const { useState, useEffect, useMemo, useRef } = React;

/* --- Logo: redrawn from the 524×156 outlined italic PNG wordmark ---
   This is an editorial "roar" lockup in stroked italic script. Inline SVG so it scales.
*/
function RoarLogo({ size = 96, color = 'currentColor', stroke = 1.6 }) {
  // Path roughly traces the outlined italic "roar" wordmark (4 stroked letterforms in italic).
  // Drawn for legibility at small sizes; not pixel-perfect to the source PNG (which we'd redraw with the client).
  return (
    <svg viewBox="0 0 320 96" width={size} height={size * 0.3} aria-label="Roar" role="img"
         style={{ display: 'block' }}>
      <g fill="none" stroke={color} strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round">
        {/* r */}
        <path d="M16 84 C 22 50, 32 28, 46 16 C 56 8, 66 8, 70 14 C 72 18, 68 22, 60 22 C 50 22, 40 28, 34 40" transform="skewX(-12)" />
        {/* o */}
        <path d="M88 60 C 88 40, 100 22, 116 22 C 130 22, 138 32, 138 46 C 138 64, 124 80, 108 80 C 94 80, 88 72, 88 60 Z" transform="skewX(-12)" />
        {/* a */}
        <path d="M188 22 C 174 22, 158 36, 158 56 C 158 72, 168 80, 180 78 C 190 76, 200 64, 202 50" transform="skewX(-12)" />
        <path d="M202 22 C 198 40, 192 64, 192 80" transform="skewX(-12)" />
        {/* r */}
        <path d="M232 84 C 238 50, 248 28, 262 16 C 272 8, 282 8, 286 14 C 288 18, 284 22, 276 22 C 266 22, 256 28, 250 40" transform="skewX(-12)" />
      </g>
    </svg>
  );
}

/* Small condensed "R" mark used for favicon-y spots and the footer monogram */
function RoarMark({ size = 32, color = 'currentColor' }) {
  return (
    <svg viewBox="0 0 64 64" width={size} height={size} aria-hidden="true">
      <circle cx="32" cy="32" r="30" fill="none" stroke={color} strokeWidth="1.2" />
      <text x="32" y="44" textAnchor="middle"
        fontFamily="Instrument Serif, serif" fontStyle="italic" fontSize="34" fill={color}>r</text>
    </svg>
  );
}

/* --- Nav --- */
function Nav({ route, setRoute, lang, setLang, openEnquiry }) {
  const items = [
    { id: 'projects', label: 'Projects' },
    { id: 'sectors',  label: 'Sectors'  },
    { id: 'studio',   label: 'Studio'   },
    { id: 'awards',   label: 'Awards'   },
    { id: 'contact',  label: 'Contact'  },
  ];
  const labels = {
    EN: items,
    AR: [
      { id: 'projects', label: 'المشاريع' },
      { id: 'sectors',  label: 'القطاعات' },
      { id: 'studio',   label: 'الاستوديو' },
      { id: 'awards',   label: 'الجوائز' },
      { id: 'contact',  label: 'تواصل' },
    ],
  };
  return (
    <nav className="nav">
      <div className="container">
        <div className="nav-inner">
          <a className="nav-logo" onClick={() => setRoute({ page: 'home' })} style={{ cursor: 'pointer' }}>
            <RoarLogo size={88} color="var(--ink)" stroke={1.4} />
            <span className="mono" style={{ fontSize: 9, letterSpacing: '0.2em', color: 'var(--muted)', marginLeft: 4 }}>
              EST. 2013<br/>DUBAI
            </span>
          </a>

          <div className="nav-links">
            {labels[lang].map(it => (
              <a key={it.id}
                 className={'nav-link ' + (route.page === it.id || (it.id === 'projects' && route.page === 'project') ? 'active' : '')}
                 onClick={() => setRoute({ page: it.id })}>
                {it.label}
              </a>
            ))}
          </div>

          <div className="nav-right">
            <div className="lang-toggle" role="tablist" aria-label="Language">
              <button className={lang === 'EN' ? 'on' : ''} onClick={() => setLang('EN')}>EN</button>
              <button className={lang === 'AR' ? 'on' : ''} onClick={() => setLang('AR')}>ع</button>
            </div>
            <button className="btn btn-primary btn-sm" onClick={openEnquiry}>
              {lang === 'AR' ? 'ابدأ مشروعًا' : 'Start a project'}
              <span className="arr">→</span>
            </button>
          </div>
        </div>
      </div>
    </nav>
  );
}

/* --- Footer --- */
function Footer({ setRoute, openEnquiry, lang }) {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-top">
          <div>
            <RoarLogo size={140} color="var(--paper)" stroke={1.2} />
            <p style={{ marginTop: 28, maxWidth: '32ch', color: 'rgba(244,240,232,0.7)', fontSize: 14, lineHeight: 1.6 }}>
              An award-winning interior design &amp; architecture studio.
              <span className="serif" style={{ color: 'var(--roar)', fontSize: 20, display: 'block', marginTop: 8 }}>
                Fifty percent wild. Fifty percent tame.
              </span>
            </p>
            <button className="btn btn-roar btn-sm" style={{ marginTop: 28 }} onClick={openEnquiry}>
              Start a project <span className="arr">→</span>
            </button>
          </div>
          <div>
            <h4>Sectors</h4>
            {SECTORS.map(s => (
              <a key={s.id} className="footer-link"
                 onClick={() => setRoute({ page: 'projects', sector: s.id })}>{s.name}</a>
            ))}
          </div>
          <div>
            <h4>Studio</h4>
            <a className="footer-link" onClick={() => setRoute({ page: 'studio' })}>About</a>
            <a className="footer-link" onClick={() => setRoute({ page: 'awards' })}>Awards &amp; Press</a>
            <a className="footer-link" onClick={() => setRoute({ page: 'projects' })}>All projects</a>
            <a className="footer-link" onClick={() => setRoute({ page: 'contact' })}>Contact</a>
          </div>
          <div>
            <h4>Contact</h4>
            <a className="footer-link" href="mailto:contact@designbyroar.com">contact@designbyroar.com</a>
            <span className="footer-link" style={{ color: 'rgba(244,240,232,0.55)', fontSize: 12 }}>
              Warehouse 44, Al Serkal Avenue,<br/>Al Quoz, Dubai, UAE
            </span>
            <span className="footer-link" style={{ color: 'rgba(244,240,232,0.4)', fontSize: 11, marginTop: 6 }}>
              Phone &amp; WhatsApp — <em>client to confirm</em>
            </span>
            <div style={{ display: 'flex', gap: 14, marginTop: 18 }}>
              {[
                ['IG','https://www.instagram.com/designbyroar/'],
                ['FB','https://www.facebook.com/designbyroar/'],
                ['LI','https://www.linkedin.com/company/pallavi-dean-interiors/'],
                ['X', 'https://twitter.com/designbyroar'],
                ['YT','https://www.youtube.com/channel/UC-2jg4F0LgqLS6_xjpZba5g'],
              ].map(([k,h]) => (
                <a key={k} href={h} target="_blank" rel="noreferrer"
                   className="mono" style={{ fontSize: 10, letterSpacing: '0.15em', color: 'rgba(244,240,232,0.7)', borderBottom: '1px solid rgba(244,240,232,0.2)', paddingBottom: 2 }}>
                  {k}
                </a>
              ))}
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} ROAR DESIGN STUDIO LLC — DUBAI</span>
          <span>EN / AR / RU* / ZH* &nbsp;·&nbsp; *coming</span>
        </div>
      </div>
    </footer>
  );
}

/* --- Project card --- */
function ProjectCard({ p, onClick, big = false }) {
  const sector = SECTORS.find(s => s.id === p.sector);
  return (
    <a className="proj-card" onClick={() => onClick(p)}>
      <div className="proj-thumb" style={ big ? { aspectRatio: '16/10' } : {} }>
        <img src={p.img} alt={p.name} loading="lazy" />
      </div>
      <div className="proj-meta">
        <div>
          <div className="proj-name">{p.name}{p.confidential && <span className="confirm">NDA</span>}</div>
          <div className="proj-loc">{p.location}</div>
        </div>
        <div className="proj-tag">{sector?.name}</div>
      </div>
    </a>
  );
}

/* --- Enquiry slide-over --- */
function EnquiryDrawer({ open, onClose }) {
  const [step, setStep] = useState(1);
  const [sent, setSent] = useState(false);
  const [data, setData] = useState({ name: '', email: '', company: '', sector: '', budget: '', timeline: '', message: '' });
  useEffect(() => { if (open) { setStep(1); setSent(false); setData({ name: '', email: '', company: '', sector: '', budget: '', timeline: '', message: '' }); } }, [open]);

  if (!open) return null;
  const submit = (e) => { e.preventDefault(); setSent(true); };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 100, display: 'grid', gridTemplateColumns: '1fr min(560px, 100%)',
    }} className="fade-in">
      <div onClick={onClose} style={{ background: 'rgba(11,10,8,0.55)' }} />
      <aside style={{ background: 'var(--paper)', overflowY: 'auto', boxShadow: '-30px 0 60px rgba(0,0,0,0.18)' }}>
        <div style={{ padding: '24px 40px', borderBottom: '1px solid var(--line-soft)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div className="eyebrow"><span className="dot"></span>Start a project · Step {Math.min(step, 3)}/3</div>
          <button onClick={onClose} className="mono" style={{ fontSize: 12, letterSpacing: '0.15em' }}>CLOSE ✕</button>
        </div>
        <div style={{ padding: '36px 40px 80px' }}>
          {!sent ? (
            <>
              <h2 className="h2" style={{ marginBottom: 8 }}>Let's talk about the brief.</h2>
              <p className="lede" style={{ marginBottom: 28 }}>
                Tell us as much or as little as you'd like. We'll come back within one working day.
              </p>

              <form className="form" onSubmit={submit}>
                {step === 1 && (
                  <>
                    <div className="form-row">
                      <div className="field">
                        <label>Your name</label>
                        <input required value={data.name} onChange={e => setData({...data, name: e.target.value})} placeholder="Pallavi Dean" />
                      </div>
                      <div className="field">
                        <label>Email</label>
                        <input required type="email" value={data.email} onChange={e => setData({...data, email: e.target.value})} placeholder="you@company.com" />
                      </div>
                    </div>
                    <div className="field">
                      <label>Company / Organisation</label>
                      <input value={data.company} onChange={e => setData({...data, company: e.target.value})} placeholder="Optional" />
                    </div>
                    <div className="row" style={{ justifyContent: 'flex-end', marginTop: 8 }}>
                      <button type="button" className="btn btn-primary" onClick={() => setStep(2)}>
                        Continue <span className="arr">→</span>
                      </button>
                    </div>
                  </>
                )}

                {step === 2 && (
                  <>
                    <div className="field">
                      <label>Sector</label>
                      <div className="choice-group">
                        {SECTORS.map(s => (
                          <button type="button" key={s.id}
                            className={'choice ' + (data.sector === s.id ? 'on' : '')}
                            onClick={() => setData({...data, sector: s.id})}>{s.name}</button>
                        ))}
                      </div>
                    </div>
                    <div className="field">
                      <label>Timeline</label>
                      <div className="choice-group">
                        {['ASAP', '3 months', '6 months', '12+ months', 'Exploring'].map(t => (
                          <button type="button" key={t}
                            className={'choice ' + (data.timeline === t ? 'on' : '')}
                            onClick={() => setData({...data, timeline: t})}>{t}</button>
                        ))}
                      </div>
                    </div>
                    <div className="field">
                      <label>Budget range <span style={{ color: 'var(--muted)', textTransform: 'none', letterSpacing: 0 }}>(optional)</span></label>
                      <div className="choice-group">
                        {['Under AED 500k', 'AED 500k–2M', 'AED 2M–10M', '10M+', 'Prefer not to say'].map(t => (
                          <button type="button" key={t}
                            className={'choice ' + (data.budget === t ? 'on' : '')}
                            onClick={() => setData({...data, budget: t})}>{t}</button>
                        ))}
                      </div>
                    </div>
                    <div className="row" style={{ justifyContent: 'space-between', marginTop: 8 }}>
                      <button type="button" className="btn-link" onClick={() => setStep(1)}>← Back</button>
                      <button type="button" className="btn btn-primary" onClick={() => setStep(3)}>
                        Continue <span className="arr">→</span>
                      </button>
                    </div>
                  </>
                )}

                {step === 3 && (
                  <>
                    <div className="field">
                      <label>Brief</label>
                      <textarea required value={data.message} onChange={e => setData({...data, message: e.target.value})}
                        placeholder="Tell us about the project — site, programme, ambition, anything inspiring you." />
                    </div>
                    <p className="mono" style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '0.1em' }}>
                      OPTIONAL: ATTACH A BRIEF (PDF / DOC) — wired to Formspree at build.
                    </p>
                    <div className="row" style={{ justifyContent: 'space-between', marginTop: 8 }}>
                      <button type="button" className="btn-link" onClick={() => setStep(2)}>← Back</button>
                      <button type="submit" className="btn btn-roar">Send the brief <span className="arr">→</span></button>
                    </div>
                  </>
                )}
              </form>
            </>
          ) : (
            <div className="fade-in">
              <div className="eyebrow"><span className="dot"></span>Brief received</div>
              <h2 className="h1" style={{ marginTop: 18 }}>
                Thank you, <span className="serif" style={{ color: 'var(--roar)' }}>{data.name || 'friend'}.</span>
              </h2>
              <p className="lede" style={{ marginTop: 24 }}>
                Your brief is on its way to the Pack. We'll come back within one working day from <strong>contact@designbyroar.com</strong>.
              </p>
              <p className="mono" style={{ fontSize: 11, color: 'var(--muted)', marginTop: 28, letterSpacing: '0.1em' }}>
                ID — RR-{Math.random().toString(36).slice(2, 8).toUpperCase()}
              </p>
              <button className="btn btn-ghost" style={{ marginTop: 28 }} onClick={onClose}>Close</button>
            </div>
          )}
        </div>
      </aside>
    </div>
  );
}

/* --- Section header --- */
function SectionHeader({ eyebrow, title, link, onLinkClick, dark = false }) {
  return (
    <div className="container" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 48, gap: 24, flexWrap: 'wrap' }}>
      <div>
        <div className="eyebrow"><span className="dot"></span>{eyebrow}</div>
        <h2 className="h1" style={{ marginTop: 16, maxWidth: '14ch', color: dark ? 'var(--paper)' : 'var(--ink)' }}>{title}</h2>
      </div>
      {link && <a className="btn-link" onClick={onLinkClick}>{link} <span className="arr">→</span></a>}
    </div>
  );
}

/* expose */
Object.assign(window, { RoarLogo, RoarMark, Nav, Footer, ProjectCard, EnquiryDrawer, SectionHeader });
