/**
 * App.jsx — Root component for the Molly Maid Virtual Estimate prototype.
 *
 * Wired for live design tweaks via the Tweaks panel:
 *   • Tier layout (Cards / Compare / Stack)
 *   • CTA color (Raspberry / Navy)
 *   • "Most Popular" highlight on/off
 *   • Cleanliness score on/off
 *   • Single price vs. price range
 *   • Density (Roomy / Compact)
 *   • Copy tone (Warm / Direct)
 *
 * Flow (4 steps): Address → Photos → Loading → Results.
 */

const { useState, useEffect } = React;

// Tweakable defaults — block contents must be valid JSON.
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "tierLayout": "cards",
  "ctaColor": "raspberry",
  "showPopular": true,
  "showScore": true,
  "priceDisplay": "single",
  "density": "roomy",
  "tone": "warm"
}/*EDITMODE-END*/;

// ── Page chrome ────────────────────────────────────────────────────────────────

function NeighborlyBar() {
  return (
    <div className="neighborly-bar">
      <div className="neighborly-bar__inner">
        <span className="neighborly-bar__brand">A Neighborly Company</span>
        <div className="neighborly-bar__links">
          <a href="#promise">Done Right Promise®</a>
          <a href="#findlocation">Find My Local Molly Maid</a>
        </div>
      </div>
    </div>
  );
}

function SiteNav() {
  return (
    <header className="site-nav" role="banner">
      <div className="site-nav__inner">
        <a href="#" className="site-nav__brand" aria-label="Molly Maid home">
          <LotusIcon size={32} />
          <span className="site-nav__wordmark">
            <span className="site-nav__wordmark-title">MOLLY MAID</span>
            <span className="site-nav__wordmark-tagline">a Neighborly® company</span>
          </span>
        </a>

        <nav className="site-nav__links" aria-label="Primary">
          <a className="site-nav__link" href="#services">Our Services</a>
          <a className="site-nav__link" href="#about">Why Molly Maid</a>
          <a className="site-nav__link" href="#promise">Done Right Promise®</a>
          <a className="site-nav__phone" href="tel:1-800-654-9647">
            <PhoneIcon /> 1-800-654-9647
          </a>
          <a className="btn-primary btn-primary--nav" href="#estimate">
            Request a Free Quote
          </a>
        </nav>
      </div>
    </header>
  );
}

function Hero({ tone }) {
  const copy = tone === 'direct'
    ? {
        eyebrow: 'Virtual Estimate · ~90 Seconds',
        title: 'Know What a Clean Will Cost — Before You Book.',
        lede: 'Type your address, share a couple of photos if you like, and we\'ll match the right service to your home. Backed by the Neighborly Done Right Promise®.',
        bullets: [
          'Pricing in under 2 minutes — no signup, no spam.',
          'Every clean follows our 44-point checklist.',
          'If it\'s not done right, we\'ll make it right.',
        ],
      }
    : {
        eyebrow: 'Virtual Estimate · No Signup Required',
        title: 'Every Home Deserves a Friend Like Molly.',
        lede: 'Get a personalized cleaning estimate in about 90 seconds. Tell us where you live, share a few photos if you\'d like, and we\'ll match the right service to your home — backed by our Neighborly Done Right Promise®.',
        bullets: [
          ['Trusted by over ', <strong key="b1">1.5 million customers</strong>, ' since 1984.'],
          ['Every clean follows our ', <strong key="b2">44-point checklist</strong>, '.'],
          [<strong key="b3">Cleaned right, or we\'ll clean again</strong>, ' — guaranteed.'],
        ],
      };

  return (
    <section className="hero">
      <div className="hero__inner">
        <div className="hero__copy">
          <p className="hero__eyebrow">{copy.eyebrow}</p>
          <h1 className="hero__title">{copy.title}</h1>
          <p className="hero__lede">{copy.lede}</p>

          <ul className="hero__bullets">
            {copy.bullets.map((b, i) => (
              <li key={i}>
                <CheckIcon size={18} color="var(--mly-raspberry)" />
                <span>{b}</span>
              </li>
            ))}
          </ul>

          <div className="hero__trust">
            <span><strong>4.8 / 5</strong> avg. customer rating</span>
            <span><strong>1.7M+</strong> cleans per year</span>
            <span><strong>40+ years</strong> of clean</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function SiteFooter() {
  return (
    <footer className="site-footer" id="about">
      <div className="site-footer__inner">
        <div className="site-footer__brand-block">
          <div className="site-nav__brand" style={{ marginBottom: 4 }}>
            <LotusIcon size={32} />
            <span className="site-nav__wordmark">
              <span className="site-nav__wordmark-title">MOLLY MAID</span>
              <span className="site-nav__wordmark-tagline">a Neighborly® company</span>
            </span>
          </div>
          <p className="site-footer__tagline">
            A clean you can count on.® Molly Maid has been giving families
            back their time since 1984.
          </p>
          <span className="site-footer__neighborly">A Neighborly Company</span>
        </div>

        <div className="site-footer__col">
          <h4>Services</h4>
          <ul>
            <li><a href="#services">Recurring House Cleaning</a></li>
            <li><a href="#services">Deep Cleaning</a></li>
            <li><a href="#services">Move-In / Move-Out</a></li>
            <li><a href="#services">Specialty Cleans</a></li>
          </ul>
        </div>

        <div className="site-footer__col">
          <h4>Company</h4>
          <ul>
            <li><a href="#about">Why Molly Maid</a></li>
            <li><a href="#promise">Done Right Promise®</a></li>
            <li><a href="#about">Ms. Molly Foundation</a></li>
            <li><a href="#about">Careers</a></li>
          </ul>
        </div>

        <div className="site-footer__col">
          <h4>Support</h4>
          <ul>
            <li><a href="tel:1-800-654-9647">1-800-654-9647</a></li>
            <li><a href="mailto:Marketing@mollymaid.com">Contact Us</a></li>
            <li><a href="#findlocation">Find My Local Molly Maid</a></li>
            <li><a href="#estimate">Request a Free Quote</a></li>
          </ul>
        </div>
      </div>

      <div className="site-footer__legal">
        <span>© {new Date().getFullYear()} Molly Maid, LLC. All rights reserved.</span>
        <span>Neighborly Done Right Promise® · Ms. Molly Foundation · Molly Maid®</span>
      </div>
    </footer>
  );
}

// ── Tweaks panel content ───────────────────────────────────────────────────

function VirtualEstimateTweaks({ t, setTweak }) {
  return (
    <TweaksPanel title="Tweaks · Pricing">
      <TweakSection label="Results layout">
        <TweakRadio
          label="Tier layout"
          value={t.tierLayout}
          options={[
            { value: 'cards',   label: 'Cards' },
            { value: 'compare', label: 'Compare' },
            { value: 'stack',   label: 'Stack' },
          ]}
          onChange={(v) => setTweak('tierLayout', v)}
        />
        <TweakRadio
          label="Price display"
          value={t.priceDisplay}
          options={[
            { value: 'single', label: 'Single' },
            { value: 'range',  label: 'Range' },
          ]}
          onChange={(v) => setTweak('priceDisplay', v)}
        />
        <TweakRadio
          label="Density"
          value={t.density}
          options={[
            { value: 'roomy',   label: 'Roomy' },
            { value: 'compact', label: 'Compact' },
          ]}
          onChange={(v) => setTweak('density', v)}
        />
      </TweakSection>

      <TweakSection label="Emphasis">
        <TweakRadio
          label="CTA color"
          value={t.ctaColor}
          options={[
            { value: 'raspberry', label: 'Raspberry' },
            { value: 'navy',      label: 'Navy' },
          ]}
          onChange={(v) => setTweak('ctaColor', v)}
        />
        <TweakToggle
          label="Highlight 'Most Popular' tier"
          value={t.showPopular}
          onChange={(v) => setTweak('showPopular', v)}
        />
        <TweakToggle
          label="Show cleanliness score"
          value={t.showScore}
          onChange={(v) => setTweak('showScore', v)}
        />
      </TweakSection>

      <TweakSection label="Voice">
        <TweakRadio
          label="Copy tone"
          value={t.tone}
          options={[
            { value: 'warm',   label: 'Warm' },
            { value: 'direct', label: 'Direct' },
          ]}
          onChange={(v) => setTweak('tone', v)}
        />
      </TweakSection>

      <TweakSection label="Demo">
        <TweakButton
          label="Jump to results (sample data)"
          onClick={() => window.dispatchEvent(new CustomEvent('demo:results'))}
        />
        <TweakButton
          secondary
          label="Reset flow to step 1"
          onClick={() => window.dispatchEvent(new CustomEvent('demo:reset'))}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// ── App ────────────────────────────────────────────────────────────────────────

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const [step, setStep]             = useState(1);
  const [address, setAddress]       = useState('');
  const [property, setProperty]     = useState(null);
  const [images, setImages]         = useState([]);
  const [analysis, setAnalysis]     = useState(null);
  const [estimates, setEstimates]   = useState(null);
  const [selectedService, setSelectedService] = useState(null);
  const [loading, setLoading]       = useState(false);
  const [error, setError]           = useState(null);

  // ── Step 1: address lookup ───────────────────────────────────────────────
  async function lookupAddress(value) {
    const trimmed = value.trim();
    if (!trimmed) return;
    setLoading(true);
    setError(null);
    try {
      const data = await window.MollyAPI.getProperty(trimmed);
      setProperty(data);
      setStep(2);
    } catch (err) {
      setError((err && err.message)
        || 'We couldn\'t find that address. Please check the spelling and try again.');
    } finally {
      setLoading(false);
    }
  }

  function handleAddressSubmit(e) {
    e.preventDefault();
    lookupAddress(address);
  }

  function handleSuggestionSelect(description) {
    setAddress(description);
    lookupAddress(description);
  }

  // ── Step 2: image upload + analysis ─────────────────────────────────────
  async function handleImagesSubmit(files) {
    setLoading(true);
    setError(null);
    try {
      let score = 50;
      let analysisData = null;

      if (files && files.length > 0) {
        analysisData = await window.MollyAPI.analyzeImages(files);
        score = analysisData.score;
        setAnalysis(analysisData);
      }

      setStep(3);
      const result = await window.MollyAPI.getEstimate({
        ...property,
        cleanlinessScore: score,
      });
      setEstimates(result.services);
      setStep(4);
    } catch (err) {
      setError((err && err.message)
        || 'Something went wrong while analyzing your photos. Please try again.');
      setStep(2);
    } finally {
      setLoading(false);
    }
  }

  function handleSkipPhotos() {
    handleImagesSubmit([]);
  }

  function handleReset() {
    setStep(1);
    setAddress('');
    setProperty(null);
    setImages([]);
    setAnalysis(null);
    setEstimates(null);
    setSelectedService(null);
    setError(null);
  }

  function handleEditAddress() {
    setStep(1);
    setProperty(null);
    setImages([]);
    setAnalysis(null);
    setEstimates(null);
    setError(null);
  }

  // Clicking a completed pill in the step indicator goes back to that step
  // without clearing collected state — the user is editing, not restarting.
  // We block forward jumps and any movement while a request is in flight.
  function handleStepJump(targetStep) {
    if (loading) return;
    if (targetStep >= step) return;
    setError(null);
    setStep(targetStep);
  }

  // Choosing a tier from the Results screen → contact-info step.
  // We stash the service so the booking page can echo plan + price back
  // and tailor its "Book" vs. "Join" copy.
  function handleChooseTier(service) {
    setSelectedService(service);
    setStep(5);
  }

  // Demo shortcuts driven by the Tweaks panel — useful for reviewing the
  // results screen without re-running address + photo steps.
  useEffect(() => {
    async function jumpToResults() {
      const sampleAddress = '142 Maple Ridge Ln, Ann Arbor, MI 48104';
      const prop = await window.MollyAPI.getProperty(sampleAddress);
      const sampleFiles = [
        { name: 'kitchen.jpg', size: 120000 },
        { name: 'bath.jpg', size: 98000 },
        { name: 'living.jpg', size: 145000 },
      ];
      const analysisData = await window.MollyAPI.analyzeImages(sampleFiles);
      const result = await window.MollyAPI.getEstimate({
        ...prop,
        cleanlinessScore: analysisData.score,
      });
      setAddress(sampleAddress);
      setProperty(prop);
      setAnalysis(analysisData);
      setEstimates(result.services);
      setStep(4);
    }
    window.addEventListener('demo:results', jumpToResults);
    window.addEventListener('demo:reset', handleReset);
    return () => {
      window.removeEventListener('demo:results', jumpToResults);
      window.removeEventListener('demo:reset', handleReset);
    };
  }, []);

  return (
    <div
      className="estimate-page"
      data-cta-color={tweaks.ctaColor}
      data-density={tweaks.density}
      data-tier-layout={tweaks.tierLayout}
    >
      <NeighborlyBar />
      <SiteNav />
      {step === 1 && <Hero tone={tweaks.tone} />}

      <main className="estimate-main" id="estimate">
        <div className="estimate-inner">
          <StepIndicator current={step} onJump={handleStepJump} />

          {step > 1 && address && (
            <AddressEditBanner
              address={address}
              onEdit={handleEditAddress}
              disabled={loading}
            />
          )}

          {error && (
            <div className="error-msg" role="alert">
              <AlertIcon /> <span>{error}</span>
            </div>
          )}

          {step === 1 && (
            <AddressStep
              address={address}
              onChange={setAddress}
              onSubmit={handleAddressSubmit}
              onSuggestionSelect={handleSuggestionSelect}
              onError={setError}
              loading={loading}
            />
          )}

          {step === 2 && (
            <PhotosStep
              property={property}
              onPropertyChange={setProperty}
              onSubmit={handleImagesSubmit}
              onSkip={handleSkipPhotos}
              loading={loading}
            />
          )}

          {step === 3 && <LoadingStep />}

          {step === 4 && estimates && (
            <ResultsStep
              property={property}
              analysis={analysis}
              services={estimates}
              onReset={handleReset}
              onChoose={handleChooseTier}
              tweaks={tweaks}
            />
          )}

          {step === 5 && (
            <BookingStep
              selectedService={selectedService}
              property={property}
              address={address}
              onBack={() => setStep(4)}
              onReset={handleReset}
            />
          )}
        </div>
      </main>

      <SiteFooter />

      <VirtualEstimateTweaks t={tweaks} setTweak={setTweak} />
    </div>
  );
}

// Mount the app
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
