// Coastal Build Group — site app
// Mounts: Tweaks panel (palette toggle) + AI Concierge widget

const COASTAL_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "a"
}/*EDITMODE-END*/;

// ─────────────────────────────────────────────────────────────────────
// AI Concierge widget — light, on-brand, multi-step lead qualifier
// ─────────────────────────────────────────────────────────────────────
const FLOW = [
  {
    key: 'project',
    bot: "Hi — I'm the Coastal concierge. I can help you scope a project in about a minute. What kind of work are you considering?",
    options: ['Kitchen', 'Bathroom', 'Secondary suite', 'Basement', 'Open-concept', 'Full home', 'Custom cabinetry', 'Other / not sure'],
  },
  {
    key: 'city',
    bot: "Great. Where in the Lower Mainland is your home?",
    options: ['Tsawwassen', 'Ladner / Delta', 'Richmond', 'Vancouver', 'Burnaby', 'Surrey / White Rock', 'Langley', 'Other'],
  },
  {
    key: 'budget',
    bot: "Roughly what budget range do you have in mind? Honest answers help us point you in the right direction.",
    options: ['$10k – $30k', '$30k – $75k', '$75k – $150k', '$150k – $300k', '$300k+', 'Not sure yet'],
  },
  {
    key: 'timeline',
    bot: "When are you hoping to begin?",
    options: ['Within 3 months', '3 – 6 months', '6 – 12 months', 'Just exploring'],
  },
];

function Concierge() {
  const [open, setOpen] = React.useState(false);
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [history, setHistory] = React.useState([{ from: 'bot', text: FLOW[0].bot }]);
  const bodyRef = React.useRef(null);

  React.useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [history, step]);

  const reset = () => {
    setStep(0);
    setAnswers({});
    setHistory([{ from: 'bot', text: FLOW[0].bot }]);
  };

  const handlePick = (option) => {
    const current = FLOW[step];
    const newAnswers = { ...answers, [current.key]: option };
    setAnswers(newAnswers);
    const newHistory = [...history, { from: 'user', text: option }];

    if (step + 1 < FLOW.length) {
      newHistory.push({ from: 'bot', text: FLOW[step + 1].bot });
      setHistory(newHistory);
      setStep(step + 1);
    } else {
      // Done — final summary
      newHistory.push({
        from: 'bot',
        text: "Thanks. Based on what you've shared, the next best step is a free, no-obligation consultation — usually about thirty minutes, in your home or by video. We'll listen first.",
      });
      setHistory(newHistory);
      setStep(FLOW.length);
    }
  };

  const isFinal = step >= FLOW.length;
  const current = !isFinal ? FLOW[step] : null;

  return (
    <>
      {!open && (
        <button className="concierge-fab" onClick={() => setOpen(true)} aria-label="Open Coastal concierge">
          <span className="pulse-dot" />
          <span>Plan your project</span>
        </button>
      )}
      {open && (
        <div className="concierge-panel" role="dialog" aria-label="Coastal concierge">
          <div className="concierge-header">
            <div>
              <h4>Coastal Build Concierge</h4>
              <p>A few quick questions to point you in the right direction.</p>
            </div>
            <button className="concierge-close" onClick={() => setOpen(false)} aria-label="Close concierge">✕</button>
          </div>
          <div className="concierge-body" ref={bodyRef}>
            {history.map((m, i) => (
              <div key={i} className={`concierge-msg ${m.from === 'user' ? 'user' : ''}`}>{m.text}</div>
            ))}
          </div>
          {!isFinal && (
            <div className="concierge-options">
              {current.options.map((opt) => (
                <button key={opt} className="concierge-option" onClick={() => handlePick(opt)}>{opt}</button>
              ))}
            </div>
          )}
          {isFinal && (
            <div className="concierge-final">
              <div className="summary">
                <strong>Project:</strong> {answers.project} &nbsp;·&nbsp;
                <strong>City:</strong> {answers.city} &nbsp;·&nbsp;
                <strong>Budget:</strong> {answers.budget} &nbsp;·&nbsp;
                <strong>Timeline:</strong> {answers.timeline}
              </div>
              <a href="#contact" className="btn btn-primary" style={{ justifyContent: 'center' }}>
                Book a free consultation <span className="arrow">→</span>
              </a>
              <a href="tel:+17788789610" className="btn btn-ghost" style={{ justifyContent: 'center' }}>
                Or call (778) 878-9610
              </a>
              <button onClick={reset} style={{ fontSize: 12, color: 'var(--text-muted)', textDecoration: 'underline', marginTop: 4 }}>Start over</button>
            </div>
          )}
        </div>
      )}
    </>
  );
}

// ─────────────────────────────────────────────────────────────────────
// App — mounts concierge + tweaks panel
// ─────────────────────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(COASTAL_DEFAULTS);

  React.useEffect(() => {
    document.documentElement.setAttribute('data-palette', t.palette);
  }, [t.palette]);

  // Concierge FAB is suppressed on the homepage (data-page="home" on <html>),
  // but kept on other pages such as Contact.
  const showConcierge = document.documentElement.dataset.page !== 'home';

  return (
    <>
      {showConcierge && <Concierge />}
      <TweaksPanel title="Coastal Tweaks">
        <TweakSection label="Color Direction">
          <TweakRadio
            label="Palette"
            value={t.palette}
            options={[
              { value: 'a', label: 'A · Sage' },
              { value: 'b', label: 'B · Navy' },
            ]}
            onChange={(v) => setTweak('palette', v)}
          />
        </TweakSection>
        <div style={{ fontSize: 11, color: 'rgba(41,38,27,0.55)', lineHeight: 1.5, marginTop: 8 }}>
          <strong style={{ display: 'block', marginBottom: 4, color: 'rgba(41,38,27,0.78)' }}>A — Linen + Sage + Bronze</strong>
          Warm, trustworthy, distinctly West Coast. Recommended.
        </div>
        <div style={{ fontSize: 11, color: 'rgba(41,38,27,0.55)', lineHeight: 1.5, marginTop: 4 }}>
          <strong style={{ display: 'block', marginBottom: 4, color: 'rgba(41,38,27,0.78)' }}>B — Ivory + Navy + Taupe</strong>
          More architectural, conservative-traditional.
        </div>
      </TweaksPanel>
    </>
  );
}

const mount = document.getElementById('coastal-mount');
if (mount) {
  ReactDOM.createRoot(mount).render(<App />);
}
