import React, { useState } from 'react';

function scoreClass(s) {
  if (s >= 70) return 'good';
  if (s >= 40) return 'ok';
  return 'bad';
}

function trendClass(t) {
  if (t === 'growing') return 'good';
  if (t === 'stable') return 'ok';
  return 'bad';
}

function severityClass(s) {
  if (s === 'critical') return 'critical';
  if (s === 'high') return 'high';
  if (s === 'medium') return 'medium';
  return 'low';
}

function threatClass(t) {
  if (t === 'high') return 'high';
  if (t === 'medium') return 'medium';
  return 'low';
}

function ScoreRing({ score }) {
  const radius = 54;
  const circumference = 2 * Math.PI * radius;
  const offset = circumference - (score / 100) * circumference;
  const cls = scoreClass(score);
  return (
    <div className="score-ring-container">
      <svg width="140" height="140" viewBox="0 0 140 140">
        <circle cx="70" cy="70" r={radius} fill="none" stroke="var(--border)" strokeWidth="10" />
        <circle cx="70" cy="70" r={radius} fill="none" stroke={cls === 'good' ? 'var(--success)' : cls === 'ok' ? 'var(--warning)' : 'var(--danger)'}
          strokeWidth="10" strokeDasharray={circumference} strokeDashoffset={offset}
          strokeLinecap="round" transform="rotate(-90 70 70)" style={{ transition: 'stroke-dashoffset 1s ease' }} />
      </svg>
      <div className={`score-ring-value ${cls}`}>{score}</div>
    </div>
  );
}

function BarChart({ items, colorKey }) {
  const maxVal = Math.max(...items.map(i => i.value), 1);
  return (
    <div className="bar-chart">
      {items.map((item, i) => (
        <div key={i} className="bar-row">
          <div className="bar-label">{item.label}</div>
          <div className="bar-track">
            <div className={`bar-fill ${colorKey || ''}`} style={{ width: `${(item.value / maxVal) * 100}%` }} />
          </div>
          <div className="bar-value">{item.display}</div>
        </div>
      ))}
    </div>
  );
}

function SectionNav({ sections, active, onSelect }) {
  return (
    <div className="section-nav">
      {sections.map((s) => (
        <button key={s.id} className={`section-nav-btn ${active === s.id ? 'active' : ''}`} onClick={() => onSelect(s.id)}>
          <span className="nav-icon">{s.icon}</span>
          <span className="nav-label">{s.label}</span>
        </button>
      ))}
    </div>
  );
}

const sections = [
  { id: 'overview', icon: '\u{1F3AF}', label: 'Overview' },
  { id: 'market', icon: '\u{1F4CA}', label: 'Market' },
  { id: 'competitors', icon: '\u{2694}\u{FE0F}', label: 'Competition' },
  { id: 'revenue', icon: '\u{1F4B0}', label: 'Revenue' },
  { id: 'swot', icon: '\u{1F9E9}', label: 'SWOT' },
  { id: 'gtm', icon: '\u{1F680}', label: 'Go-to-Market' },
  { id: 'funding', icon: '\u{1F3E6}', label: 'Funding' },
  { id: 'feasibility', icon: '\u{1F527}', label: 'Feasibility' },
  { id: 'risks', icon: '\u{26A0}\u{FE0F}', label: 'Risks' },
  { id: 'pivot', icon: '\u{1F504}', label: 'Pivots' },
  { id: 'plan', icon: '\u{1F4C5}', label: '90-Day Plan' },
  { id: 'pitch', icon: '\u{1F4DD}', label: 'Pitch Deck' },
];

export default function Results({ data, onReset }) {
  const a = data.analysis;
  const [activeSection, setActiveSection] = useState('overview');

  const safeArray = (val) => Array.isArray(val) ? val : [];

  return (
    <div className="results">
      <SectionNav sections={sections} active={activeSection} onSelect={setActiveSection} />

      {/* === OVERVIEW === */}
      {activeSection === 'overview' && (
        <>
          <div className="verdict-card">
            <div className="idea-name">{a.ideaName}</div>
            <div className="one-liner">{a.oneLiner}</div>
            <ScoreRing score={a.overallScore} />
            <div className="score-label">Viability Score</div>
            <div className={`verdict-badge ${a.verdict}`}>{(a.verdict || '').replace(/_/g, ' ')}</div>
            <p className="verdict-explain">{a.verdictExplanation}</p>
          </div>

          {a.similarSuccesses && (
            <div className="card">
              <h3>{'\u{1F3C6}'} Similar Success Stories</h3>
              <div className="success-grid">
                {safeArray(a.similarSuccesses).map((s, i) => (
                  <div key={i} className="success-item">
                    <div className="success-company">{s.company}</div>
                    <div className="success-detail"><strong>Similarity:</strong> {s.similarity}</div>
                    <div className="success-detail"><strong>Outcome:</strong> {s.outcome}</div>
                    <div className="success-lesson">{'\u{1F4A1}'} {s.lessonToApply}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </>
      )}

      {/* === MARKET SIZING === */}
      {activeSection === 'market' && a.marketSizing && (
        <>
          <div className="card">
            <h3>{'\u{1F4CA}'} TAM / SAM / SOM Market Sizing</h3>
            <div className="market-funnel">
              <div className="funnel-level tam">
                <div className="funnel-header">
                  <span className="funnel-label">TAM</span>
                  <span className="funnel-value">{a.marketSizing.tam}</span>
                </div>
                <div className="funnel-desc">{a.marketSizing.tamReasoning}</div>
              </div>
              <div className="funnel-level sam">
                <div className="funnel-header">
                  <span className="funnel-label">SAM</span>
                  <span className="funnel-value">{a.marketSizing.sam}</span>
                </div>
                <div className="funnel-desc">{a.marketSizing.samReasoning}</div>
              </div>
              <div className="funnel-level som">
                <div className="funnel-header">
                  <span className="funnel-label">SOM</span>
                  <span className="funnel-value">{a.marketSizing.som}</span>
                </div>
                <div className="funnel-desc">{a.marketSizing.somReasoning}</div>
              </div>
            </div>
          </div>
          <div className="card">
            <h3>{'\u{1F4C8}'} Market Dynamics</h3>
            <div className="stat-grid">
              <div className="stat">
                <div className="stat-label">Growth Rate (CAGR)</div>
                <div className="stat-value accent">{a.marketSizing.marketGrowthRate}</div>
              </div>
              <div className="stat">
                <div className="stat-label">Market Trend</div>
                <div className={`stat-value trend-${trendClass(a.marketSizing.marketTrend)}`}>{a.marketSizing.marketTrend}</div>
              </div>
              <div className="stat">
                <div className="stat-label">Timing</div>
                <div className="stat-value">{a.marketSizing.timing}</div>
              </div>
              <div className="stat">
                <div className="stat-label">Timing Analysis</div>
                <div className="stat-value sm">{a.marketSizing.timingNote}</div>
              </div>
            </div>
          </div>
        </>
      )}

      {/* === COMPETITOR ANALYSIS === */}
      {activeSection === 'competitors' && a.competitorAnalysis && (
        <>
          <div className="card">
            <h3>{'\u{2694}\u{FE0F}'} Direct Competitors</h3>
            <div className="competitor-grid">
              {safeArray(a.competitorAnalysis.directCompetitors).map((c, i) => (
                <div key={i} className="competitor-card">
                  <div className="comp-header">
                    <span className="comp-name">{c.name}</span>
                    <span className="comp-funding">{c.funding}</span>
                  </div>
                  <div className="comp-row"><span className="comp-label">Strength</span><span>{c.strength}</span></div>
                  <div className="comp-row"><span className="comp-label">Weakness</span><span>{c.weakness}</span></div>
                  <div className="comp-row"><span className="comp-label">Market Share</span><span>{c.marketShare}</span></div>
                </div>
              ))}
            </div>
          </div>
          <div className="card">
            <h3>{'\u{1F310}'} Indirect Competitors</h3>
            {safeArray(a.competitorAnalysis.indirectCompetitors).map((c, i) => (
              <div key={i} className="indirect-comp">
                <div className="ic-header">
                  <span className="ic-name">{c.name}</span>
                  <span className={`threat-badge ${threatClass(c.threat)}`}>{c.threat} threat</span>
                </div>
                <div className="ic-detail">{c.howTheyCompete}</div>
              </div>
            ))}
          </div>
          <div className="card">
            <h3>{'\u{1F440}'} Potential Future Competitors</h3>
            {safeArray(a.competitorAnalysis.potentialCompetitors).map((c, i) => (
              <div key={i} className="indirect-comp">
                <div className="ic-header">
                  <span className="ic-name">{c.name}</span>
                  <span className={`threat-badge ${threatClass(c.likelihood)}`}>{c.likelihood} likelihood</span>
                </div>
                <div className="ic-detail">Possible entry: {c.timeframe}</div>
              </div>
            ))}
          </div>
          <div className="card">
            <h3>{'\u{1F6E1}\u{FE0F}'} Your Competitive Edge</h3>
            <div className="stat-grid">
              <div className="stat full-width">
                <div className="stat-label">Competitive Advantage</div>
                <div className="stat-value sm">{a.competitorAnalysis.competitiveAdvantage}</div>
              </div>
              <div className="stat">
                <div className="stat-label">Moat Possibility</div>
                <div className="stat-value">{a.competitorAnalysis.moatPossibility}</div>
              </div>
              <div className="stat">
                <div className="stat-label">Moat Strategy</div>
                <div className="stat-value sm">{a.competitorAnalysis.moatStrategy}</div>
              </div>
            </div>
          </div>
        </>
      )}

      {/* === REVENUE MODEL === */}
      {activeSection === 'revenue' && a.revenueModel && (
        <>
          <div className="card">
            <h3>{'\u{1F4B0}'} Revenue Projections</h3>
            <div className="revenue-bars">
              {a.revenueModel.projectedRevenue && (
                <div className="projection-grid">
                  <div className="projection-item y1">
                    <div className="proj-year">Year 1</div>
                    <div className="proj-value">{a.revenueModel.projectedRevenue.year1}</div>
                  </div>
                  <div className="projection-item y2">
                    <div className="proj-year">Year 2</div>
                    <div className="proj-value">{a.revenueModel.projectedRevenue.year2}</div>
                  </div>
                  <div className="projection-item y3">
                    <div className="proj-year">Year 3</div>
                    <div className="proj-value">{a.revenueModel.projectedRevenue.year3}</div>
                  </div>
                </div>
              )}
            </div>
          </div>
          <div className="card">
            <h3>{'\u{1F4B5}'} Business Model & Pricing</h3>
            <div className="stat-grid">
              <div className="stat">
                <div className="stat-label">Primary Model</div>
                <div className="stat-value accent">{a.revenueModel.primaryModel}</div>
              </div>
              <div className="stat">
                <div className="stat-label">Break-even Timeline</div>
                <div className="stat-value">{a.revenueModel.breakEvenTimeline}</div>
              </div>
              <div className="stat full-width">
                <div className="stat-label">Pricing Strategy</div>
                <div className="stat-value sm">{a.revenueModel.pricingStrategy}</div>
              </div>
            </div>
          </div>
          {a.revenueModel.unitEconomics && (
            <div className="card">
              <h3>{'\u{1F4CA}'} Unit Economics</h3>
              <div className="stat-grid three">
                <div className="stat highlight-green">
                  <div className="stat-label">LTV</div>
                  <div className="stat-value">{a.revenueModel.unitEconomics.ltv}</div>
                </div>
                <div className="stat highlight-amber">
                  <div className="stat-label">CAC</div>
                  <div className="stat-value">{a.revenueModel.unitEconomics.cac}</div>
                </div>
                <div className="stat highlight-purple">
                  <div className="stat-label">LTV:CAC Ratio</div>
                  <div className="stat-value">{a.revenueModel.unitEconomics.ltvCacRatio}</div>
                </div>
                <div className="stat">
                  <div className="stat-label">Payback Period</div>
                  <div className="stat-value">{a.revenueModel.unitEconomics.paybackPeriod}</div>
                </div>
                <div className="stat">
                  <div className="stat-label">Gross Margin</div>
                  <div className="stat-value">{a.revenueModel.unitEconomics.grossMargin}</div>
                </div>
              </div>
            </div>
          )}
        </>
      )}

      {/* === SWOT ANALYSIS === */}
      {activeSection === 'swot' && a.swotAnalysis && (
        <div className="card swot-card">
          <h3>{'\u{1F9E9}'} SWOT Analysis</h3>
          <div className="swot-grid">
            <div className="swot-box strengths">
              <div className="swot-title">{'\u{1F4AA}'} Strengths</div>
              <ul>{safeArray(a.swotAnalysis.strengths).map((s, i) => <li key={i}>{s}</li>)}</ul>
            </div>
            <div className="swot-box weaknesses">
              <div className="swot-title">{'\u{26A0}\u{FE0F}'} Weaknesses</div>
              <ul>{safeArray(a.swotAnalysis.weaknesses).map((w, i) => <li key={i}>{w}</li>)}</ul>
            </div>
            <div className="swot-box opportunities">
              <div className="swot-title">{'\u{1F31F}'} Opportunities</div>
              <ul>{safeArray(a.swotAnalysis.opportunities).map((o, i) => <li key={i}>{o}</li>)}</ul>
            </div>
            <div className="swot-box threats">
              <div className="swot-title">{'\u{1F525}'} Threats</div>
              <ul>{safeArray(a.swotAnalysis.threats).map((t, i) => <li key={i}>{t}</li>)}</ul>
            </div>
          </div>
        </div>
      )}

      {/* === GO TO MARKET === */}
      {activeSection === 'gtm' && a.goToMarket && (
        <>
          <div className="card">
            <h3>{'\u{1F680}'} Go-to-Market Strategy</h3>
            <div className="gtm-timeline">
              {['phase1', 'phase2', 'phase3'].map((phase, i) => {
                const p = a.goToMarket[phase];
                if (!p) return null;
                return (
                  <div key={i} className={`gtm-phase phase-${i + 1}`}>
                    <div className="phase-marker">{i + 1}</div>
                    <div className="phase-content">
                      <div className="phase-name">{p.name}</div>
                      <div className="phase-strategy">{p.strategy}</div>
                      <div className="phase-meta">
                        <span className="phase-channels">{'\u{1F4E2}'} {safeArray(p.channels).join(', ')}</span>
                        <span className="phase-target">{'\u{1F3AF}'} {p.targetMetric}</span>
                        <span className="phase-budget">{'\u{1F4B2}'} {p.budget}</span>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="card">
            <h3>{'\u{1F4E3}'} Viral & Adoption Strategy</h3>
            <div className="stat-grid">
              <div className="stat">
                <div className="stat-label">Viral Potential</div>
                <div className="stat-value">{a.goToMarket.viralPotential}</div>
              </div>
              <div className="stat">
                <div className="stat-label">Early Adopters</div>
                <div className="stat-value sm">{a.goToMarket.earlyAdopters}</div>
              </div>
              <div className="stat full-width">
                <div className="stat-label">Viral Mechanism</div>
                <div className="stat-value sm">{a.goToMarket.viralMechanism}</div>
              </div>
            </div>
          </div>
        </>
      )}

      {/* === FUNDING ASSESSMENT === */}
      {activeSection === 'funding' && a.fundingAssessment && (
        <div className="card">
          <h3>{'\u{1F3E6}'} Funding Assessment</h3>
          <div className="funding-header">
            <div className="funding-stage">
              <div className="stage-label">Current Stage</div>
              <div className="stage-value">{a.fundingAssessment.currentStage}</div>
            </div>
            <div className="funding-stage">
              <div className="stage-label">Readiness</div>
              <div className={`stage-value readiness-${a.fundingAssessment.readiness?.replace(/\s/g, '-')}`}>{a.fundingAssessment.readiness}</div>
            </div>
          </div>
          <div className="stat-grid">
            <div className="stat highlight-green">
              <div className="stat-label">Recommended Raise</div>
              <div className="stat-value">{a.fundingAssessment.recommendedRaise}</div>
            </div>
            <div className="stat highlight-purple">
              <div className="stat-label">Valuation Range</div>
              <div className="stat-value">{a.fundingAssessment.valuationRange}</div>
            </div>
          </div>
          <div className="milestones">
            <div className="milestone-title">Key Milestones Needed</div>
            {safeArray(a.fundingAssessment.keyMilestonesNeeded).map((m, i) => (
              <div key={i} className="milestone-item">
                <span className="milestone-num">{i + 1}</span>
                <span>{m}</span>
              </div>
            ))}
          </div>
          <div className="stat-grid" style={{ marginTop: '1rem' }}>
            <div className="stat">
              <div className="stat-label">Best Investor Fit</div>
              <div className="stat-value sm">{safeArray(a.fundingAssessment.investorFit).join(', ')}</div>
            </div>
            <div className="stat">
              <div className="stat-label">Pitch Strength</div>
              <div className="stat-value sm">{a.fundingAssessment.pitchStrength}</div>
            </div>
          </div>
        </div>
      )}

      {/* === FEASIBILITY === */}
      {activeSection === 'feasibility' && a.feasibility && (
        <div className="card">
          <h3>{'\u{1F527}'} Technical Feasibility</h3>
          <div className="stat-grid">
            <div className="stat">
              <div className="stat-label">Technical Complexity</div>
              <div className={`stat-value complexity-${a.feasibility.technicalComplexity}`}>{a.feasibility.technicalComplexity}</div>
            </div>
            <div className="stat">
              <div className="stat-label">Time to MVP</div>
              <div className="stat-value">{a.feasibility.timeToMVP}</div>
            </div>
            <div className="stat">
              <div className="stat-label">Estimated Cost</div>
              <div className="stat-value">{a.feasibility.estimatedCost}</div>
            </div>
            <div className="stat">
              <div className="stat-label">Tech Stack</div>
              <div className="stat-value sm">{a.feasibility.techStack}</div>
            </div>
            <div className="stat full-width">
              <div className="stat-label">Team Needed</div>
              <div className="stat-value sm">{safeArray(a.feasibility.teamNeeded).join(' \u{2022} ')}</div>
            </div>
            <div className="stat full-width">
              <div className="stat-label">Technical Note</div>
              <div className="stat-value sm">{a.feasibility.technicalNote}</div>
            </div>
            <div className="stat full-width">
              <div className="stat-label">Biggest Technical Risk</div>
              <div className="stat-value sm">{a.feasibility.biggestTechnicalRisk}</div>
            </div>
          </div>
        </div>
      )}

      {/* === RISK MATRIX === */}
      {activeSection === 'risks' && a.riskMatrix && (
        <div className="card">
          <h3>{'\u{26A0}\u{FE0F}'} Risk Matrix</h3>
          <div className="risk-matrix-grid">
            <div className="rm-header">
              <span className="rm-h-risk">Risk</span>
              <span className="rm-h-cat">Category</span>
              <span className="rm-h-prob">Probability</span>
              <span className="rm-h-impact">Impact</span>
              <span className="rm-h-sev">Severity</span>
            </div>
            {safeArray(a.riskMatrix).map((r, i) => (
              <div key={i} className="rm-row">
                <div className="rm-risk">
                  <div className="rm-risk-name">{r.risk}</div>
                  <div className="rm-mitigation">{'\u{1F6E1}\u{FE0F}'} {r.mitigation}</div>
                </div>
                <span className="rm-cat">{r.category}</span>
                <span className={`rm-badge ${severityClass(r.probability)}`}>{r.probability}</span>
                <span className={`rm-badge ${severityClass(r.impact)}`}>{r.impact}</span>
                <span className={`rm-badge ${severityClass(r.severity)}`}>{r.severity}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* === PIVOT SUGGESTIONS === */}
      {activeSection === 'pivot' && a.pivotSuggestions && (
        <div className="card">
          <h3>{'\u{1F504}'} Pivot Suggestions</h3>
          <div className="pivot-grid">
            {safeArray(a.pivotSuggestions).map((p, i) => (
              <div key={i} className="pivot-card">
                <div className="pivot-header">
                  <span className="pivot-name">{p.pivot}</span>
                  <span className={`effort-badge ${p.effort}`}>{p.effort} effort</span>
                </div>
                <div className="pivot-reasoning">{p.reasoning}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* === 90-DAY PLAN === */}
      {activeSection === 'plan' && a.ninetyDayPlan && (
        <div className="card">
          <h3>{'\u{1F4C5}'} 90-Day Validation Plan</h3>
          <div className="plan-timeline">
            {safeArray(a.ninetyDayPlan).map((p, i) => (
              <div key={i} className="plan-item">
                <div className="plan-week-marker">
                  <div className="plan-dot" />
                  <div className="plan-week">{p.week}</div>
                </div>
                <div className="plan-content">
                  <div className="plan-action">{p.action}</div>
                  <div className="plan-meta">
                    <span>{'\u{1F4E6}'} <strong>Deliverable:</strong> {p.deliverable}</span>
                    <span>{'\u{1F3AF}'} <strong>Goal:</strong> {p.goal}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* === PITCH DECK === */}
      {activeSection === 'pitch' && a.pitchDeckOutline && (
        <div className="card">
          <h3>{'\u{1F4DD}'} Pitch Deck Outline</h3>
          <div className="pitch-grid">
            {safeArray(a.pitchDeckOutline).map((slide, i) => (
              <div key={i} className="pitch-slide">
                <div className="slide-number">Slide {slide.slide}</div>
                <div className="slide-title">{slide.title}</div>
                <div className="slide-content">{slide.content}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      <button className="btn-reset" onClick={onReset}>{'\u{1F504}'} Validate Another Idea</button>
    </div>
  );
}
