/* ===== Design Reveal — hero output with 3-way visual toggle + guided tour ===== */

const TOUR_STEPS = [
  { id: 'patio',  title: 'Flagstone patio & fire pit', body: 'Centered on your back door, 220 ft² of flagstone — large enough for 6-person dining and a fire pit on cool evenings. Rear-easement compliant.' },
  { id: 'beds',   title: 'Perennial borders', body: 'Two organic-edge beds flank the patio with drought-tolerant perennials (echinacea, rudbeckia) and feather-reed grass. Full-sun ready, pollinator friendly.' },
  { id: 'screen', title: 'Privacy screen', body: 'Two serviceberry trees anchor the bed ends — Pacific NW native, four-season interest, mature at 15 ft. They\'ll soften the neighbor\'s fence by year 3.' },
  { id: 'lawn',   title: 'Central lawn', body: 'Fescue blend scaled to your "half & half" preference. Low water once established; mow every 10–14 days.' },
  { id: 'trees',  title: 'Existing trees preserved', body: 'We designed around all 6 existing trees. No planting within 6 ft of trunks; the firs keep the west fence in dappled shade.' },
];

const STYLE_MODES = [
  { id: 'watercolor', label: 'Watercolor', icon: 'palette' },
  { id: 'render',     label: 'Photo render', icon: 'camera' },
  { id: 'cad',        label: 'CAD linework', icon: 'ruler' },
];

const DesignReveal = ({ onContinue }) => {
  const [generating, setGenerating] = React.useState(true);
  const [progress, setProgress] = React.useState(0);
  const [mode, setMode] = React.useState('watercolor');
  const [tour, setTour] = React.useState(false);
  const [tourStep, setTourStep] = React.useState(0);
  const [activeArea, setActiveArea] = React.useState(null);
  const [hoveredArea, setHoveredArea] = React.useState(null);
  const selectedArea = activeArea ? PLANTING_AREAS.find(a => a.id === activeArea) : null;

  React.useEffect(() => {
    const steps = ['Analyzing 8b microclimate…', 'Placing hardscape footprints…', 'Selecting plant palette…', 'Laying out plant quantities…', 'Finalizing design…'];
    let i = 0;
    const t = setInterval(() => {
      setProgress(((i + 1) / steps.length) * 100);
      i++;
      if (i >= steps.length) {
        clearInterval(t);
        setTimeout(() => setGenerating(false), 400);
      }
    }, 700);
    return () => clearInterval(t);
  }, []);

  if (generating) {
    return (
      <div className="screen screen-fade-in">
        <StepRail current="design" />
        <div className="generating">
          <div className="generating__bloom">
            <BlossomMark size={64} color="#3D4421" accent="#D97757" />
          </div>
          <div className="eyebrow" style={{ justifyContent: 'center' }}>
            <span className="eyebrow__dot" />Generating your design
          </div>
          <h2 className="serif" style={{ fontSize: 44, marginTop: 14, letterSpacing: '-0.022em', textAlign: 'center' }}>
            Planting your vision.
          </h2>
          <p className="muted" style={{ marginTop: 12, textAlign: 'center', fontSize: 15, maxWidth: 440 }}>
            Novale is composing a plan around your site, style, and the way you'll actually use the space.
          </p>
          <div className="generating__bar">
            <div className="generating__bar-fill" style={{ width: `${progress}%` }} />
          </div>
          <div className="generating__facts">
            <div className="generating__fact"><Icon name="sparkles" size={14} /><span>38 plants across 9 species</span></div>
            <div className="generating__fact"><Icon name="droplets" size={14} /><span>Drip-ready, zone 8b</span></div>
            <div className="generating__fact"><Icon name="flower-2" size={14} /><span>Native pollinators</span></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="screen screen-fade-in">
      <StepRail current="design" />

      <div className="design">
        <div className="design__canvas">
          <div className="design__canvas-inner" data-mode={mode} data-paneled={!!selectedArea}>
            <BaseMap
              layers={{ boundary: true, structures: true, trees: true, sun: false, soil: false, labels: mode !== 'render' }}
              plants={true}
              mode={mode}
              width={1000}
              height={640}
            />

            <PlantingAreaOverlay
              activeId={activeArea}
              hoveredId={hoveredArea}
              setHoveredId={setHoveredArea}
              onSelect={setActiveArea}
            />

            {!selectedArea && !tour && (
              <div className="pa-hint">
                <span className="pa-hint__dot" />
                Tap a planting area to edit
              </div>
            )}

            {selectedArea && (
              <PlantingAreaPanel area={selectedArea} onClose={() => setActiveArea(null)} />
            )}

            {tour && (
              <div className="tour-overlay">
                <TourCallout step={TOUR_STEPS[tourStep]} index={tourStep} total={TOUR_STEPS.length}
                  onPrev={() => setTourStep(s => Math.max(0, s - 1))}
                  onNext={() => setTourStep(s => Math.min(TOUR_STEPS.length - 1, s + 1))}
                  onClose={() => setTour(false)}
                />
              </div>
            )}
          </div>

          <div className="design__canvas-chrome">
            <div className="segment" style={{ width: 320 }}>
              {STYLE_MODES.map(m => (
                <button key={m.id} className="segment__btn" data-active={mode === m.id} onClick={() => setMode(m.id)}>
                  <Icon name={m.icon} size={13} /> <span style={{ marginLeft: 6 }}>{m.label}</span>
                </button>
              ))}
            </div>
            <div className="row" style={{ gap: 8 }}>
              <button className="btn btn--ghost btn--sm" onClick={() => { setTour(true); setTourStep(0); }}>
                <Icon name="play-circle" size={14} /> Guided tour
              </button>
              <button className="btn btn--ghost btn--sm"><Icon name="message-square" size={14} /> Refine with AI</button>
            </div>
          </div>
        </div>

        <aside className="design__side">
          <div style={{ padding: '24px 24px 0' }}>
            <div className="row row--between" style={{ alignItems: 'flex-start' }}>
              <div>
                <div className="eyebrow"><span className="eyebrow__dot" />Your design · Draft 1</div>
                <h3 className="serif" style={{ fontSize: 26, marginTop: 8, letterSpacing: '-0.014em', lineHeight: 1.2 }}>
                  Modern native back yard
                </h3>
              </div>
              <button className="btn btn--text btn--sm"><Icon name="more-horizontal" size={14} /></button>
            </div>
            <div className="row" style={{ marginTop: 10, gap: 6, flexWrap: 'wrap' }}>
              <span className="badge badge--foliage">Modern · Native</span>
              <span className="badge badge--sun">Full sun</span>
              <span className="badge badge--stone">Zone 8b</span>
            </div>
          </div>

          <div className="design__tabs">
            <button className="design__tab" data-active={true}>Plants</button>
            <button className="design__tab">Materials</button>
            <button className="design__tab">Notes</button>
          </div>

          <div className="design__list">
            {PLANT_LIST.map((p, i) => (
              <div key={i} className="plant-row">
                <div className="plant-row__swatch" style={{ background: p.color }}>
                  <div className="plant-row__code">{p.code}</div>
                </div>
                <div className="plant-row__body">
                  <div className="plant-row__name">{p.name}</div>
                  <div className="plant-row__latin">{p.latin}</div>
                  <div className="plant-row__tags">
                    {p.tags.map((t, j) => <span key={j} className="plant-row__tag">{t}</span>)}
                  </div>
                </div>
                <div className="plant-row__qty">
                  <div className="plant-row__qty-num">{p.qty}</div>
                  <div className="plant-row__qty-unit">{p.unit}</div>
                </div>
              </div>
            ))}
          </div>

          <div className="design__footer">
            <div className="design__summary">
              <div>
                <div className="analysis__stat-label">Total plants</div>
                <div className="analysis__stat-value" style={{ fontSize: 22 }}>38</div>
              </div>
              <div>
                <div className="analysis__stat-label">Species</div>
                <div className="analysis__stat-value" style={{ fontSize: 22 }}>9</div>
              </div>
              <div>
                <div className="analysis__stat-label">Est. materials</div>
                <div className="analysis__stat-value" style={{ fontSize: 22 }}>$2,140</div>
              </div>
            </div>
            <button className="btn btn--accent btn--lg" style={{ width: '100%' }} onClick={onContinue}>
              Love it — choose a plan
              <Icon name="arrow-right" size={16} />
            </button>
            <button className="btn btn--ghost btn--sm" style={{ width: '100%', marginTop: 8 }}>
              <Icon name="refresh-ccw" size={14} /> Generate another variation
            </button>
          </div>
        </aside>
      </div>
    </div>
  );
};

const TourCallout = ({ step, index, total, onPrev, onNext, onClose }) => {
  const positions = {
    patio:  { left: '50%', top: '80%' },
    beds:   { left: '18%', top: '80%' },
    screen: { left: '18%', top: '88%' },
    lawn:   { left: '50%', top: '45%' },
    trees:  { left: '82%', top: '35%' },
  };
  const pos = positions[step.id] || { left: '50%', top: '50%' };
  return (
    <>
      <div className="tour-pin" style={{ left: pos.left, top: pos.top }}>
        <div className="tour-pin__dot" />
        <div className="tour-pin__ring" />
      </div>
      <div className="tour-card">
        <div className="row row--between">
          <div className="eyebrow"><span className="eyebrow__dot" />Tour · {index + 1} of {total}</div>
          <button className="btn btn--text btn--sm" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <h4 className="serif" style={{ fontSize: 22, marginTop: 10, letterSpacing: '-0.012em', lineHeight: 1.2 }}>{step.title}</h4>
        <p style={{ fontSize: 14, color: 'var(--fg-secondary)', marginTop: 8, lineHeight: 1.55 }}>{step.body}</p>
        <div className="row row--between" style={{ marginTop: 16 }}>
          <button className="btn btn--ghost btn--sm" onClick={onPrev} disabled={index === 0}><Icon name="arrow-left" size={14} /> Prev</button>
          <div className="row" style={{ gap: 4 }}>
            {Array.from({ length: total }).map((_, i) => (
              <div key={i} className="tour-dot" data-active={i === index} />
            ))}
          </div>
          {index < total - 1
            ? <button className="btn btn--primary btn--sm" onClick={onNext}>Next <Icon name="arrow-right" size={14} /></button>
            : <button className="btn btn--accent btn--sm" onClick={onClose}>Done <Icon name="check" size={14} /></button>}
        </div>
      </div>
    </>
  );
};

const PLANT_LIST = [
  { code: 'AM', name: 'Serviceberry', latin: 'Amelanchier × grandiflora', qty: 2, unit: 'trees', tags: ['Native', 'Full sun', 'Pollinator'], color: '#3D4421' },
  { code: 'MO', name: 'Oregon grape', latin: 'Mahonia aquifolium', qty: 4, unit: 'shrubs', tags: ['Native', 'Drought-tolerant', 'Evergreen'], color: '#6B7541' },
  { code: 'EC', name: 'Purple coneflower', latin: 'Echinacea purpurea', qty: 4, unit: 'perennials', tags: ['Pollinator', 'Full sun'], color: '#D97757' },
  { code: 'PA', name: 'Feather reed grass', latin: 'Calamagrostis × acutiflora', qty: 4, unit: 'grasses', tags: ['Full sun', 'Low water'], color: '#FDE68A' },
  { code: 'RU', name: 'Black-eyed susan', latin: 'Rudbeckia fulgida', qty: 8, unit: 'perennials', tags: ['Pollinator', 'Full sun'], color: '#F59E0B' },
  { code: 'TH', name: 'Creeping thyme', latin: 'Thymus serpyllum', qty: 12, unit: 'groundcover', tags: ['Low water', 'Fragrant'], color: '#B0BB7E' },
  { code: 'SA', name: 'Salvia', latin: 'Salvia nemorosa \'Caradonna\'', qty: 4, unit: 'perennials', tags: ['Pollinator', 'Deer-resistant'], color: '#7C3923' },
];

Object.assign(window, { DesignReveal });
