// ConfiguratorPage.jsx — "Design your oven" — professional configurator.
//
// Lets the customer choose oven model, mosaic finish, fuel, size and stand, see a
// live summary, then request a quote via an inline form on the same page. On
// submit it composes an email template (subject + body) from all the selections
// and shows it back to the user. Email SENDING is not configured yet — the
// composed message is displayed and logged so the wiring is ready to drop in.
(function () {
  const { useState, useRef } = React;

  // ---- Options -------------------------------------------------------------
  const MODELS = [
    { id: 'verona', name: 'Verona',       kind: 'Residential', note: 'For homes and enthusiasts' },
    { id: 'napoli', name: 'Napoli',       kind: 'Commercial',  note: 'For restaurants and high volume' },
    { id: 'custom', name: 'Custom build', kind: 'Bespoke',     note: 'Designed to your space' },
  ];

  // Curated to cover the full range (metallics, blends, colours, neutrals)
  // without overwhelming. Grouped so it reads as organised choice.
  const FINISHES = [
    // Metallics
    { id: 'gold',    label: 'Magic gold',    img: 'images/tiles_hd/49-D-Magic-Gold-Hex.jpg',     group: 'Metallics' },
    { id: 'copper',  label: 'Magic copper',  img: 'images/tiles_hd/48-D-Magic-Copper-Hex.jpg',   group: 'Metallics' },
    { id: 'bronze',  label: 'Magic bronze',  img: 'images/tiles_hd/45-D-Magic-Bronze-Hex.jpg',   group: 'Metallics' },
    { id: 'silver',  label: 'Magic silver',  img: 'images/tiles_hd/47-D-Magic-Silver-Hex.jpg',   group: 'Metallics' },
    { id: 'black',   label: 'Magic black',   img: 'images/tiles_hd/46-D-Magic-Black-Hex.jpg',    group: 'Metallics' },
    // Blends
    { id: 'classic', label: 'Classic blend', img: 'images/tiles_hd/Magic-Blend-Classic-Hex.jpg', group: 'Blends' },
    { id: 'trend',   label: 'Trend blend',   img: 'images/tiles_hd/Magic-Blend-Trend-Hex.jpg',   group: 'Blends' },
    { id: 'aura',    label: 'Aura blend',    img: 'images/tiles_hd/Aura-Classic.jpg',            group: 'Blends' },
    { id: 'elegant', label: 'Elegant blend', img: 'images/tiles_hd/Edna-Elegant.jpg',            group: 'Blends' },
    { id: 'rome',    label: 'Rome marble',   img: 'images/tiles_hd/Magic-Blend-Rome.jpg',        group: 'Blends' },
    // Colours
    { id: 'laguna',  label: 'Laguna blue',   img: 'images/tiles_hd/Aura-Laguna.jpg',             group: 'Colours' },
    { id: 'smoky',   label: 'Smoky blue',    img: 'images/tiles_hd/Aura-Smoky-Blue.jpg',         group: 'Colours' },
    { id: 'red',     label: 'Soft red',      img: 'images/tiles_hd/Bijou-Soft-Red.jpg',          group: 'Colours' },
    // Neutrals
    { id: 'white',   label: 'Pearl white',   img: 'images/tiles_hd/Bijou-White.jpg',             group: 'Neutrals' },
    { id: 'cotton',  label: 'Cotton cream',  img: 'images/tiles_hd/Aura-Cotton.jpg',             group: 'Neutrals' },
  ];

  const FUELS = [
    { id: 'wood', label: 'Wood-fired' },
    { id: 'gas',  label: 'Gas-fired' },
    { id: 'both', label: 'Wood + gas' },
  ];

  const SIZES = [
    { id: 's80',  label: '80 cm',  note: 'Home / small kitchen' },
    { id: 's100', label: '100 cm', note: 'Most popular' },
    { id: 's120', label: '120 cm', note: 'High volume / commercial' },
  ];

  const STANDS = [
    { id: 'stand', label: 'With stand' },
    { id: 'nostand', label: 'Countertop (no stand)' },
  ];

  // ---- Small building blocks ----------------------------------------------
  const eyebrowStyle = {
    fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '.14em',
    textTransform: 'uppercase', color: 'var(--fg-3)', fontWeight: 600, margin: '0 0 14px',
  };
  const inputStyle = {
    width: '100%', background: 'var(--bg)', border: '1.5px solid var(--border-strong)',
    borderRadius: 'var(--r-md)', padding: '13px 15px', color: 'var(--fg-1)',
    fontFamily: 'var(--font-body)', fontSize: 'var(--t-body)', outline: 'none',
  };

  function OptionRow({ children }) {
    return <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>{children}</div>;
  }

  function Chip({ selected, onClick, children, sub }) {
    return (
      <button type="button" onClick={onClick}
        style={{
          cursor: 'pointer', textAlign: 'left', padding: '12px 16px',
          borderRadius: 'var(--r-md)', fontFamily: 'var(--font-body)',
          border: '1.5px solid ' + (selected ? 'var(--accent)' : 'var(--border-strong)'),
          background: selected ? 'color-mix(in srgb, var(--accent) 10%, transparent)' : 'transparent',
          color: 'var(--fg-1)', transition: 'border-color .18s, background .18s', minWidth: 0,
        }}>
        <div style={{ fontWeight: 600, fontSize: 'var(--t-sm)' }}>{children}</div>
        {sub && <div className="tf-small" style={{ marginTop: 2 }}>{sub}</div>}
      </button>
    );
  }

  function Section({ n, title, children }) {
    return (
      <div style={{ paddingBlock: 26, borderTop: '1px solid var(--border)' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 16 }}>
          <span style={{ fontFamily: 'var(--font-display)', color: 'var(--accent)', fontSize: '1.1rem', fontWeight: 600 }}>{n}</span>
          <h3 className="tf-h4" style={{ margin: 0 }}>{title}</h3>
        </div>
        {children}
      </div>
    );
  }

  // ---- Email template ------------------------------------------------------
  function buildEmail(cfg, contact) {
    const model = MODELS.find(m => m.id === cfg.model);
    const finish = FINISHES.find(f => f.id === cfg.finish);
    const fuel = FUELS.find(f => f.id === cfg.fuel);
    const size = SIZES.find(s => s.id === cfg.size);
    const stand = STANDS.find(s => s.id === cfg.stand);

    const subject = `Quote request — ${model ? model.name : 'Oven'}${finish ? ' · ' + finish.label : ''}`;
    const lines = [
      'New "Design your oven" quote request',
      '====================================',
      '',
      'OVEN CONFIGURATION',
      `  Model:   ${model ? model.name + ' (' + model.kind + ')' : '—'}`,
      `  Finish:  ${finish ? finish.label : '—'}`,
      `  Fuel:    ${fuel ? fuel.label : '—'}`,
      `  Size:    ${size ? size.label : '—'}`,
      `  Stand:   ${stand ? stand.label : '—'}`,
      '',
      'CUSTOMER',
      `  Name:    ${contact.name || '—'}`,
      `  Email:   ${contact.email || '—'}`,
      `  Phone:   ${contact.phone || '—'}`,
      `  Location:${contact.location ? ' ' + contact.location : ' —'}`,
      '',
      'NOTES',
      `  ${contact.notes ? contact.notes : '—'}`,
      '',
      '--',
      'Sent from the Terraforno "Design your oven" configurator.',
    ];
    return { subject, body: lines.join('\n'), to: 'hello@terrafornoovens.com' };
  }

  // ---- Page ----------------------------------------------------------------
  function ConfiguratorPage({ go }) {
    const [cfg, setCfg] = useState({ model: 'verona', finish: 'gold', fuel: 'both', size: 's100', stand: 'stand' });
    const [showForm, setShowForm] = useState(false);
    const [contact, setContact] = useState({ name: '', email: '', phone: '', location: '', notes: '' });
    const [sent, setSent] = useState(null); // holds the composed email once submitted
    const formRef = useRef(null);

    const set = (k, v) => setCfg(c => ({ ...c, [k]: v }));
    const setC = (k, v) => setContact(c => ({ ...c, [k]: v }));

    const model = MODELS.find(m => m.id === cfg.model);
    const finish = FINISHES.find(f => f.id === cfg.finish);
    const fuel = FUELS.find(f => f.id === cfg.fuel);
    const size = SIZES.find(s => s.id === cfg.size);
    const stand = STANDS.find(s => s.id === cfg.stand);

    const openForm = () => {
      setShowForm(true);
      setTimeout(() => { if (formRef.current) formRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 60);
    };

    const submit = (e) => {
      e.preventDefault();
      const email = buildEmail(cfg, contact);
      // Email sending is not configured yet — log the composed message so the
      // wiring is ready. Replace this with a real send (API / mailto / form service).
      console.log('[Terraforno] Quote email to send:\n', email.to, '\n', email.subject, '\n\n', email.body);
      setSent(email);
      setTimeout(() => { if (formRef.current) formRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 60);
    };

    const summaryRows = [
      ['Model', model ? model.name : '—'],
      ['Finish', finish ? finish.label : '—'],
      ['Fuel', fuel ? fuel.label : '—'],
      ['Size', size ? size.label : '—'],
      ['Stand', stand ? stand.label : '—'],
    ];

    return (
      <div style={{ background: 'var(--bg)', minHeight: '100vh' }}>

        {/* Header */}
        <div style={{ background: 'var(--surface)', borderBottom: '1px solid var(--border)', padding: '52px 0 40px', textAlign: 'center' }}>
          <div className="tf-wrap">
            <p style={{ ...eyebrowStyle, color: 'var(--accent)', letterSpacing: '.18em', marginBottom: 12 }}>Build your oven</p>
            <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(32px,4.6vw,52px)', fontWeight: 600, color: 'var(--fg-1)', margin: '0 0 14px', lineHeight: 1.1 }}>Design your oven</h1>
            <p className="tf-body" style={{ color: 'var(--fg-2)', maxWidth: 560, margin: '0 auto' }}>
              Choose your model, mosaic finish and options, then request a quote. We'll come back with pricing, lead time and everything you need to know.
            </p>
          </div>
        </div>

        {/* Layout: options (left) + summary (right) */}
        <div className="tf-wrap" style={{ padding: '40px 0 76px' }}>
          <div className="cfg-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 340px', gap: 44, alignItems: 'start' }}>

            {/* Options */}
            <div>
              <Section n="01" title="Choose your model">
                <OptionRow>
                  {MODELS.map(m => (
                    <Chip key={m.id} selected={cfg.model === m.id} onClick={() => set('model', m.id)} sub={m.note}>{m.name}</Chip>
                  ))}
                </OptionRow>
              </Section>

              <Section n="02" title="Choose your mosaic finish">
                {['Metallics', 'Blends', 'Colours', 'Neutrals'].map(groupName => (
                  <div key={groupName} style={{ marginBottom: 22 }}>
                    <p className="tf-small" style={{ color: 'var(--fg-3)', letterSpacing: '.1em', textTransform: 'uppercase', fontWeight: 600, fontSize: 11, margin: '0 0 10px' }}>{groupName}</p>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(88px, 1fr))', gap: 12 }}>
                      {FINISHES.filter(f => f.group === groupName).map(f => {
                        const on = cfg.finish === f.id;
                        return (
                          <button key={f.id} type="button" onClick={() => set('finish', f.id)}
                            style={{ appearance: 'none', border: 'none', background: 'none', padding: 0, cursor: 'pointer', textAlign: 'center' }}>
                            <span style={{
                              display: 'block', aspectRatio: '1', borderRadius: 'var(--r-md)', overflow: 'hidden',
                              boxShadow: on ? '0 0 0 2px var(--bg), 0 0 0 4px var(--accent)' : 'var(--sh-1)',
                              backgroundImage: `url(${f.img})`, backgroundSize: 'cover', backgroundPosition: 'center',
                              transition: 'box-shadow .18s',
                            }} />
                            <span className="tf-small" style={{ display: 'block', marginTop: 7, fontWeight: on ? 600 : 400, color: on ? 'var(--fg-1)' : 'var(--fg-2)', fontSize: 12 }}>{f.label}</span>
                          </button>
                        );
                      })}
                    </div>
                  </div>
                ))}
                <p className="tf-small" style={{ marginTop: 4, color: 'var(--fg-3)' }}>
                  Every dome is finished by hand. Want a bespoke pattern or colour not shown here? Mention it in your quote request.
                </p>
              </Section>

              <Section n="03" title="Fuel">
                <OptionRow>
                  {FUELS.map(f => <Chip key={f.id} selected={cfg.fuel === f.id} onClick={() => set('fuel', f.id)}>{f.label}</Chip>)}
                </OptionRow>
              </Section>

              <Section n="04" title="Size">
                <OptionRow>
                  {SIZES.map(s => <Chip key={s.id} selected={cfg.size === s.id} onClick={() => set('size', s.id)} sub={s.note}>{s.label}</Chip>)}
                </OptionRow>
              </Section>

              <Section n="05" title="Stand">
                <OptionRow>
                  {STANDS.map(s => <Chip key={s.id} selected={cfg.stand === s.id} onClick={() => set('stand', s.id)}>{s.label}</Chip>)}
                </OptionRow>
              </Section>
            </div>

            {/* Summary (sticky) */}
            <aside style={{ position: 'sticky', top: 96 }}>
              <div className="tf-card" style={{ padding: '24px 24px 26px', overflow: 'hidden' }}>
                <div style={{ aspectRatio: '4/3', borderRadius: 'var(--r-md)', backgroundImage: `url(${finish ? finish.img : ''})`, backgroundSize: 'cover', backgroundPosition: 'center', marginBottom: 18 }} />
                <p style={eyebrowStyle}>Your configuration</p>
                <h3 className="tf-h3" style={{ margin: '0 0 16px' }}>{model ? model.name : 'Your oven'}</h3>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                  {summaryRows.map(([k, v]) => (
                    <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '10px 0', borderTop: '1px solid var(--border)' }}>
                      <span className="tf-small" style={{ color: 'var(--fg-3)' }}>{k}</span>
                      <span className="tf-small" style={{ color: 'var(--fg-1)', fontWeight: 600, textAlign: 'right' }}>{v}</span>
                    </div>
                  ))}
                </div>
                <TFButton variant="primary" size="lg" block arrow onClick={openForm} style={{ marginTop: 22 }}>Get a quote</TFButton>
                <p className="tf-small" style={{ textAlign: 'center', margin: '12px 0 0', color: 'var(--fg-3)' }}>Free, no obligation. We reply within 2 working days.</p>
              </div>
            </aside>
          </div>

          {/* Inline quote form / confirmation */}
          {showForm && (
            <div ref={formRef} style={{ maxWidth: 720, margin: '56px auto 0', scrollMarginTop: 90 }}>
              {sent ? (
                <div className="tf-card" style={{ padding: 'clamp(28px,4vw,48px)', textAlign: 'center' }}>
                  <span style={{ width: 64, height: 64, borderRadius: '50%', background: 'color-mix(in srgb, var(--accent) 16%, transparent)', display: 'grid', placeItems: 'center', margin: '0 auto 20px', color: 'var(--accent)' }}><Icon name="check" size={30} /></span>
                  <h2 className="tf-h3" style={{ margin: '0 0 10px' }}>Your request is ready.</h2>
                  <p className="tf-body" style={{ maxWidth: 440, margin: '0 auto 24px', color: 'var(--fg-2)' }}>
                    Thanks{contact.name ? ', ' + contact.name.split(' ')[0] : ''} — here's the summary we've prepared for our team. We'll be in touch within 2 working days.
                  </p>
                  {/* Preview of the email that will be sent (sending not yet configured) */}
                  <div style={{ textAlign: 'left', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', padding: '18px 20px', marginBottom: 24 }}>
                    <div className="tf-small" style={{ color: 'var(--fg-3)', marginBottom: 8 }}>To: {sent.to} &nbsp;·&nbsp; Subject: {sent.subject}</div>
                    <pre className="tf-mono" style={{ margin: 0, whiteSpace: 'pre-wrap', fontSize: 12.5, color: 'var(--fg-2)', lineHeight: 1.6 }}>{sent.body}</pre>
                  </div>
                  <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
                    <TFButton variant="primary" arrow onClick={() => go('product')}>Browse the ovens</TFButton>
                    <TFButton variant="outline" onClick={() => { setSent(null); setShowForm(false); }}>Start over</TFButton>
                  </div>
                </div>
              ) : (
                <div className="tf-card" style={{ padding: 'clamp(24px,3vw,40px)' }}>
                  <p style={eyebrowStyle}>Almost there</p>
                  <h2 className="tf-h3" style={{ margin: '0 0 6px' }}>Request your quote</h2>
                  <p className="tf-small" style={{ margin: '0 0 22px', color: 'var(--fg-2)' }}>
                    Your configuration — <strong style={{ color: 'var(--fg-1)' }}>{model ? model.name : 'Oven'}, {finish ? finish.label : ''}, {fuel ? fuel.label.toLowerCase() : ''}, {size ? size.label : ''}</strong> — will be sent with your details.
                  </p>
                  <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                      <label style={{ display: 'block' }}>
                        <span style={eyebrowStyle}>Full name</span>
                        <input style={inputStyle} required value={contact.name} onChange={e => setC('name', e.target.value)} placeholder="enter name here" />
                      </label>
                      <label style={{ display: 'block' }}>
                        <span style={eyebrowStyle}>Email</span>
                        <input type="email" style={inputStyle} required value={contact.email} onChange={e => setC('email', e.target.value)} placeholder="xyz@email.com" />
                      </label>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                      <label style={{ display: 'block' }}>
                        <span style={eyebrowStyle}>Phone</span>
                        <input type="tel" style={inputStyle} value={contact.phone} onChange={e => setC('phone', e.target.value)} placeholder="enter phone number" />
                      </label>
                      <label style={{ display: 'block' }}>
                        <span style={eyebrowStyle}>City / location</span>
                        <input style={inputStyle} required value={contact.location} onChange={e => setC('location', e.target.value)} placeholder="enter city / location" />
                      </label>
                    </div>
                    <label style={{ display: 'block' }}>
                      <span style={eyebrowStyle}>Anything else? (optional)</span>
                      <textarea rows={3} style={{ ...inputStyle, resize: 'vertical' }} value={contact.notes} onChange={e => setC('notes', e.target.value)} placeholder="Timeline, bespoke finish, restaurant covers, delivery questions…" />
                    </label>
                    <TFButton type="submit" variant="primary" size="lg" block arrow>Send my quote request</TFButton>
                    <p className="tf-small" style={{ textAlign: 'center', margin: 0, color: 'var(--fg-3)' }}>We read every request and reply personally.</p>
                  </form>
                </div>
              )}
            </div>
          )}
        </div>

        <style>{`
          @media (max-width: 820px) {
            .cfg-grid { grid-template-columns: 1fr !important; }
            .cfg-grid aside { position: static !important; }
          }
        `}</style>
      </div>
    );
  }

  window.ConfiguratorPage = ConfiguratorPage;
})();
