// RiverSafe — Main App Shell

// ── Storage version check ────────────────────────────────────────────────
// Runs once, synchronously, before any component reads localStorage.
// On version mismatch: clears only RiverSafe keys (rs_*, riversafe_*), so
// stale state from earlier alpha builds can't put users in untested states.
(function checkStorageVersion() {
  try {
    const stored = localStorage.getItem('rs_storage_version');
    if (stored !== String(RS_STORAGE_VERSION)) {
      const doomed = [];
      for (let i = 0; i < localStorage.length; i++) {
        const k = localStorage.key(i);
        if (k && (k.indexOf('rs_') === 0 || k.indexOf('riversafe_') === 0)) doomed.push(k);
      }
      doomed.forEach((k) => localStorage.removeItem(k));
      localStorage.setItem('rs_storage_version', String(RS_STORAGE_VERSION));
    }
  } catch (e) {}
})();

const STEPS = [
{ label: 'Plan your visit', short: 'Plan visit' },
{ label: 'Share your skills', short: 'Skills' },
{ label: 'Pick your activity tools', short: 'Tools' },
{ label: 'Visit assessment', short: 'Assessment' }];


function validateStep(step, data) {
  const errors = [];
  if (step === 0) {
    if (!data.river) errors.push('Select a river destination to continue');
    if (!data.activity) errors.push('Select your activity to continue');
    if (data.waterTemp < 32 || data.waterTemp > 100) errors.push('Enter a realistic water temperature');
  }
  if (step === 1) {
    if (!data.swimmingLevel || data.swimmingLevel < 1) errors.push('Select a swimming level to continue');
  }
  if (step === 2) {
    if (data.equipment.lifejacket === 'none') errors.push('Consider selecting a personal flotation device');
  }
  return errors;
}

function StepIndicator({ currentStep, completedSteps }) {
  return (
    <div className="usa-step-indicator" aria-label="Assessment progress">
      <div className="usa-step-indicator__heading">
        <span className="usa-step-indicator__heading-text">{STEPS[currentStep].short}</span>
        <span className="usa-step-indicator__heading-counter">Step {currentStep + 1} of {STEPS.length}</span>
      </div>
      <ol className="usa-step-indicator__segments">
        {STEPS.map((step, i) => {
          const isComplete = completedSteps.has(i);
          const isCurrent = i === currentStep;
          const cls = isComplete ? 'usa-step-indicator__segment--complete' :
          isCurrent ? 'usa-step-indicator__segment--current' :
          '';
          return (
            <li
              key={i}
              className={`usa-step-indicator__segment ${cls}`}
              aria-current={isCurrent ? 'step' : undefined}
              aria-label={`Step ${i + 1}: ${step.label}${isComplete ? ' — completed' : isCurrent ? ' — current' : ''}`}>
              
              <div className="usa-step-indicator__segment-indicator" aria-hidden="true">
                {isComplete ? '✓' : i + 1}
              </div>
              <span className="usa-step-indicator__segment-label">{step.short}</span>
            </li>);

        })}
      </ol>
    </div>);

}

function BottomNav({ currentStep, canAdvance, onPrev, onNext, onRestart, errors }) {
  const isLast = currentStep === STEPS.length - 1;
  return (
    <nav className="rs-bottom-nav" aria-label="Assessment navigation">
      {currentStep > 0 && !isLast ?
      <button
        className="usa-button usa-button--outline"
        onClick={onPrev}
        aria-label="Go to previous step">
        
          ← Previous
        </button> :

      <div></div>
      }

      {isLast ?
      <button
        className="usa-button usa-button--primary"
        onClick={onRestart}
        aria-label="Start a new assessment"
        style={{ flex: 1 }}>
        
          New assessment
        </button> :

      <button
        className="usa-button usa-button--primary"
        onClick={onNext}
        disabled={!canAdvance}
        aria-label={canAdvance ? 'Continue to next step' : 'Complete required fields to continue'}
        style={{ flex: currentStep === 0 ? 1 : undefined }}>
        
          Continue →
        </button>
      }
    </nav>);

}

function ValidationErrors({ errors }) {
  if (!errors.length) return null;
  return (
    <div className="rs-validation" role="alert" aria-live="polite">
      {errors.map((e, i) =>
      <p key={i} className="rs-validation-item">{e}</p>
      )}
    </div>);

}

function getInitialShowIntro() {
  try {
    return localStorage.getItem('riversafe_intro_seen') !== 'true';
  } catch (e) {
    return true;
  }
}

function App() {
  const [showIntro, setShowIntro] = React.useState(getInitialShowIntro);
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({ ...DEFAULT_DATA });
  const [attempted, setAttempted] = React.useState(false);
  const [completedSteps, setCompletedSteps] = React.useState(new Set());
  const [conditions, setConditions] = React.useState(null);
  const [conditionsLoading, setConditionsLoading] = React.useState(false);
  const [showImprove, setShowImprove] = React.useState(false);

  // Fetch live conditions whenever river changes
  React.useEffect(() => {
    if (!data.river) {setConditions(null);return;}
    setConditionsLoading(true);
    fetchRiverConditions(data.river).then((result) => {
      setConditions(result);
      setConditionsLoading(false);
      if (result) {
        const updates = {};
        if (result.waterTempF !== null && result.waterTempF !== undefined) updates.waterTemp = result.waterTempF;
        if (result.airTempF !== null && result.airTempF !== undefined) updates.airTemp = result.airTempF;
        if (Object.keys(updates).length > 0) setData((prev) => ({ ...prev, ...updates }));
      }
    });
  }, [data.river]);

  // Recompute completed steps whenever data changes
  React.useEffect(() => {
    const done = new Set();
    for (let i = 0; i < STEPS.length - 1; i++) {
      if (validateStep(i, data).length === 0) done.add(i);
    }
    // Results step is always "completable" if we reached it
    if (step === STEPS.length - 1) done.add(STEPS.length - 1);
    setCompletedSteps(done);
  }, [data, step]);

  function update(partial) {
    setData((prev) => ({ ...prev, ...partial }));
    setAttempted(false);
  }

  function handleRefreshConditions() {
    if (!data.river) return;
    invalidateRiverCache(data.river);
    setConditions(null);
    setConditionsLoading(true);
    fetchRiverConditions(data.river).then((result) => {
      setConditions(result);
      setConditionsLoading(false);
      if (result) {
        const updates = {};
        if (result.waterTempF !== null && result.waterTempF !== undefined) updates.waterTemp = result.waterTempF;
        if (result.airTempF !== null && result.airTempF !== undefined) updates.airTemp = result.airTempF;
        if (Object.keys(updates).length > 0) setData((prev) => ({ ...prev, ...updates }));
      }
    });
  }

  const errors = validateStep(step, data);
  const canAdvance = errors.length === 0;

  function handleNext() {
    if (!canAdvance) {setAttempted(true);return;}
    setAttempted(false);
    setStep((s) => Math.min(s + 1, STEPS.length - 1));
    window.scrollTo({ top: 0 });
  }

  function handlePrev() {
    setAttempted(false);
    setShowImprove(false);
    setStep((s) => Math.max(s - 1, 0));
    window.scrollTo({ top: 0 });
  }

  function handleRestart() {
    setData({ ...DEFAULT_DATA });
    setStep(0);
    setAttempted(false);
    setCompletedSteps(new Set());
    setConditions(null);
    setConditionsLoading(false);
    setShowImprove(false);
    window.scrollTo({ top: 0 });
  }

  function handleShowImprove() {
    setShowImprove(true);
    window.scrollTo({ top: 0 });
  }

  function handleBackFromImprove() {
    setShowImprove(false);
    window.scrollTo({ top: 0 });
  }

  function handleFinishIntro() {
    try {
      localStorage.setItem('riversafe_intro_seen', 'true');
    } catch (e) {}
    setShowIntro(false);
  }

  function handleReopenIntro() {
    setShowIntro(true);
    window.scrollTo({ top: 0 });
  }

  if (showIntro) {
    return <IntroScreens onFinish={handleFinishIntro} />;
  }

  return (
    <div className="rs-app">
      {/* Header */}
      <header className="rs-header" role="banner">
        <div className="rs-header__icon">
          <img src="rs-logo-icon.png" alt="" aria-hidden="true" />
        </div>
        <div className="rs-header__wordmark">
          <h1 className="rs-header__title">RiverSafe</h1>
          <p className="rs-header__subtitle">River safety assessment</p>
        </div>
        <button type="button" className="rs-header__info" onClick={handleReopenIntro} aria-label="About RiverSafe">ⓘ</button>
      </header>

      {/* Step Indicator */}
      {!(step === 3 && showImprove) &&
      <StepIndicator currentStep={step} completedSteps={completedSteps} />
      }

      {/* Main content */}
      <main className="rs-content" id="main-content" role="main">
        {step === 3 && showImprove ?
        <StepImprove data={data} onBack={handleBackFromImprove} /> :

        <React.Fragment>
            {step === 0 && <StepPlan data={data} onUpdate={update} conditions={conditions} conditionsLoading={conditionsLoading} onRefreshConditions={handleRefreshConditions} />}
            {step === 1 && <StepSkills data={data} onUpdate={update} />}
            {step === 2 && <StepTools data={data} onUpdate={update} />}
            {step === 3 && <ErrorBoundary><StepResults data={data} conditions={conditions} onImprove={handleShowImprove} /></ErrorBoundary>}

            {/* Inline validation (steps 0–2 only) */}
            {step < STEPS.length - 1 && attempted &&
          <ValidationErrors errors={errors} />
          }

            {/* Step 2: PFD soft warning (non-blocking) */}
            {step === 2 && data.equipment.lifejacket === 'none' && !attempted &&
          <div className="rs-validation" style={{ marginTop: 'var(--sp-2)' }}>
                <p className="rs-validation-item" style={{ color: 'var(--theme-color-warning-dark)' }}>
                  Proceeding without a PFD significantly increases your safety risk.
                </p>
              </div>
          }
          </React.Fragment>
        }
      </main>

      {/* Emergency callout — always visible except on the Improve Your Trip screen */}
      {!(step === 3 && showImprove) &&
      <div className="rs-emergency-footer" role="note">
          <strong>Emergency?</strong> Call 911 or your local emergency services immediately.
        </div>
      }

      {/* Bottom navigation */}
      {!(step === 3 && showImprove) &&
      <BottomNav
        currentStep={step}
        canAdvance={canAdvance}
        onPrev={handlePrev}
        onNext={handleNext}
        onRestart={handleRestart}
        errors={attempted ? errors : []} />
      }
    </div>);

}

const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<ErrorBoundary><App /></ErrorBoundary>);