
const { useState, useMemo } = React;

const AREA_ICONS = {
  '1A': () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M3 4h12M3 9h9M3 14h6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>,
  '1B': () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="9" r="6" stroke="currentColor" strokeWidth="1.6"/><path d="M6 9h6M9 6v6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>,
  '1C': () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M9 3v7M6 7l3 3 3-3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/><path d="M4 13h10" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>,
  '2':  () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M5 13l4-8 4 8M6.5 10h5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  '3A': () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="9" r="5" stroke="currentColor" strokeWidth="1.6"/><path d="M9 6v3l2 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>,
  '3B': () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M5 5h8v10H5zM3 5l2-2h8l2 2" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/></svg>,
  '4':  () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="7" cy="7" r="3" stroke="currentColor" strokeWidth="1.5"/><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="1.5"/></svg>,
  '5A': () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M6 14V8l-2-3h10l-2 3v6" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/><path d="M4 14h10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>,
  '5B': () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M9 3c-2 2-5 4-4 7 1 2 3 3 4 3s3-1 4-3c1-3-2-5-4-7z" stroke="currentColor" strokeWidth="1.5"/></svg>,
  '5C': () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="11" r="4" stroke="currentColor" strokeWidth="1.5"/><path d="M7 7V4M11 7V4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>,
  '6':  () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M3 9c0-3.3 2.7-6 6-6s6 2.7 6 6-2.7 6-6 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/><path d="M9 3v12M3 9h6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>,
};

function ProgressRing({ completed, total, size = 88 }) {
  const stroke = 7, r = (size - stroke) / 2;
  const circ = 2 * Math.PI * r;
  const pct = total > 0 ? completed / total : 0;
  const done = pct === 1;
  return (
    <div className="progress-ring-wrap" style={{ width: size, height: size, position: 'relative' }}>
      <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--divider)" strokeWidth={stroke} />
        <circle cx={size/2} cy={size/2} r={r} fill="none"
          stroke={done ? 'var(--green)' : 'var(--accent)'}
          strokeWidth={stroke} strokeLinecap="round"
          strokeDasharray={circ} strokeDashoffset={circ * (1 - pct)}
          style={{ transition: 'stroke-dashoffset 0.6s cubic-bezier(.4,0,.2,1)' }}
        />
      </svg>
      <div className="progress-ring-label">
        <span className="ring-num">{completed}</span>
        <span className="ring-den">/{total}</span>
      </div>
    </div>
  );
}

function AreaCard({ area, selected, autoSelected, inPlan, onToggle, expanded, onToggleExpand }) {
  const Icon = AREA_ICONS[area.id] || AREA_ICONS['1A'];
  const isDone = area.id === '5C'
    ? autoSelected.length > 0
    : selected.length >= (area.rule === 'two_disciplines' ? 2 : area.required);
  const isAuto = autoSelected.length > 0 && selected.length === 0;

  const deptGroups = useMemo(() => {
    const groups = {};
    for (const c of area.courses) {
      if (!groups[c.prefix]) groups[c.prefix] = [];
      groups[c.prefix].push(c);
    }
    return Object.entries(groups).sort((a, b) => a[0].localeCompare(b[0]));
  }, [area.courses]);

  const effective = [...new Set([...selected, ...autoSelected])];

  if (area.id === '5C') {
    return (
      <div className={`getc-card ${isDone ? 'done' : ''}`}>
        <div className="getc-card-header">
          <div className="getc-card-icon"><Icon /></div>
          <div className="getc-card-info">
            <div className="getc-card-area-id">Area {area.id}</div>
            <div className="getc-card-name">{area.name}</div>
            {isDone
              ? <div className="getc-card-summary">{autoSelected[0]} satisfies this</div>
              : <div className="getc-card-req-text">Pick a 5A or 5B course with a lab component</div>}
          </div>
          <div className="getc-card-status-icon">
            {isDone
              ? <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="8" fill="var(--green-bg)"/><path d="M6 10l2.5 2.5L14 7" stroke="var(--green)" strokeWidth="2" strokeLinecap="round"/></svg>
              : <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="8" stroke="var(--divider)" strokeWidth="1.5"/></svg>}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={`getc-card ${isDone ? 'done' : ''} ${isAuto && isDone ? 'auto-done' : ''}`}>
      <div className="getc-card-header" onClick={() => onToggleExpand(area.id)} style={{ cursor: 'pointer' }}>
        <div className="getc-card-icon"><Icon /></div>
        <div className="getc-card-info">
          <div className="getc-card-area-id">Area {area.id}</div>
          <div className="getc-card-name">{area.name}</div>
          {isDone
            ? <div className="getc-card-summary">{effective.join(', ')}{isAuto ? ' · auto-filled' : ''}</div>
            : <div className="getc-card-req-text">
                {area.rule === 'two_disciplines' ? '2 courses from 2 different disciplines' : `${area.required} course required`}
                {` · ${area.courses.length} options`}
              </div>}
        </div>
        <div className="getc-card-status-icon">
          {isDone
            ? <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="8" fill="var(--green-bg)"/><path d="M6 10l2.5 2.5L14 7" stroke="var(--green)" strokeWidth="2" strokeLinecap="round"/></svg>
            : <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="8" stroke="var(--divider)" strokeWidth="1.5"/></svg>}
          <span className="getc-chevron">{expanded ? '▴' : '▾'}</span>
        </div>
      </div>

      {expanded && (
        <div className="getc-expanded-body">
          {deptGroups.map(([dept, courses]) => (
            <div key={dept} className="getc-dept-group">
              <div className="getc-dept-label">{dept}</div>
              <div className="getc-chip-row">
                {courses.map(c => {
                  const isSel = selected.includes(c.key) || autoSelected.includes(c.key);
                  const isInPlan = inPlan.has(c.key);
                  return (
                    <button key={c.key}
                      className={`getc-chip ${isSel ? 'selected' : ''} ${isInPlan && !isSel ? 'in-plan' : ''}`}
                      onClick={() => onToggle(area.id, c.key, area.rule === 'two_disciplines' ? 2 : area.required)}
                    >
                      {isSel && <svg width="11" height="11" viewBox="0 0 11 11" fill="none"><path d="M2 5.5l2.5 2.5L9 3" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>}
                      {c.key}
                      {c.is_lab && <span className="getc-lab-tag">LAB</span>}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
          {effective.length > 0 && (
            <div className="getc-selection-footer">
              <span className="getc-sel-label">Selected:</span>
              {effective.map(k => (
                <span key={k} className="getc-sel-tag">
                  {k}
                  <button className="getc-sel-remove" onClick={() => onToggle(area.id, k, area.rule === 'two_disciplines' ? 2 : area.required)}>×</button>
                </span>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function CalGETCView({ profile, onUpdateProfile }) {
  const [mode, setMode] = useState(profile.calgetcMode || 'full');
  const [expandedId, setExpandedId] = useState(null);

  const inPlan = useMemo(() => {
    const keys = new Set(Object.values(profile.semesters || {}).flat());
    Object.keys(profile.courseStatuses || {}).forEach(k => keys.add(k));
    return keys;
  }, [profile]);

  // Auto-detect from plan
  const autoSelections = useMemo(() => {
    const auto = {};
    for (const area of window.MOCK_CALGETC) {
      if (area.id === '5C') continue;
      const matches = area.courses.filter(c => inPlan.has(c.key));
      if (matches.length > 0) {
        const needed = area.rule === 'two_disciplines' ? 2 : area.required;
        auto[area.id] = matches.slice(0, needed).map(c => c.key);
      }
    }
    // 5C: auto if any 5A or 5B with is_lab
    const area5a = window.MOCK_CALGETC.find(a => a.id === '5A');
    const area5b = window.MOCK_CALGETC.find(a => a.id === '5B');
    const labCourses = [...(area5a?.courses || []), ...(area5b?.courses || [])].filter(c => c.is_lab && inPlan.has(c.key));
    if (labCourses.length > 0) auto['5C'] = [labCourses[0].key];
    return auto;
  }, [inPlan]);

  const selections = profile.calgetcSelections || {};

  const handleToggle = (areaId, courseKey, max) => {
    const current = selections[areaId] || [];
    let next;
    if (current.includes(courseKey)) {
      next = current.filter(k => k !== courseKey);
    } else if (current.length < max) {
      next = [...current, courseKey];
    } else {
      next = [...current.slice(1), courseKey];
    }
    onUpdateProfile({ calgetcSelections: { ...selections, [areaId]: next } });
  };

  const handleAutoFill = () => {
    const newSel = {};
    for (const [areaId, keys] of Object.entries(autoSelections)) {
      newSel[areaId] = keys;
    }
    onUpdateProfile({ calgetcSelections: newSel });
  };

  const BREADTH_AREAS = ['1A', '1B', '2', '3A', '3B', '4', '5A', '5B'];
  const visibleAreas = mode === 'breadth'
    ? window.MOCK_CALGETC.filter(a => BREADTH_AREAS.includes(a.id))
    : window.MOCK_CALGETC;

  const completedCount = visibleAreas.filter(area => {
    if (area.id === '5C') return (autoSelections['5C'] || []).length > 0;
    const sel = [...(selections[area.id] || []), ...(autoSelections[area.id] || [])];
    const unique = [...new Set(sel)];
    return unique.length >= (area.rule === 'two_disciplines' ? 2 : area.required);
  }).length;

  const totalAreas = visibleAreas.length;

  return (
    <div className="calgetc-view">
      <div className="calgetc-header">
        <div className="calgetc-header-left">
          <h2 className="calgetc-title">Cal-GETC Tracker</h2>
          <p className="calgetc-sub">
            {mode === 'full' ? 'Complete all 11 areas for full GE certification' : '7-course minimum breadth pattern for UC eligibility'}
          </p>
          <div className="calgetc-mode-btns">
            <button className={`calgetc-mode-btn ${mode === 'full' ? 'active' : ''}`} onClick={() => setMode('full')}>Full Cal-GETC</button>
            <button className={`calgetc-mode-btn ${mode === 'breadth' ? 'active' : ''}`} onClick={() => setMode('breadth')}>7-Course Breadth</button>
          </div>
        </div>
        <div className="calgetc-header-right">
          <ProgressRing completed={completedCount} total={totalAreas} />
        </div>
      </div>

      <div className="calgetc-actions-row">
        <button className="calgetc-autofill-btn" onClick={handleAutoFill}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2 7c0-2.76 2.24-5 5-5s5 2.24 5 5-2.24 5-5 5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/><path d="M7 5v2l1.5 1.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
          Auto-fill from plan
        </button>
        <button className="calgetc-clear-btn" onClick={() => onUpdateProfile({ calgetcSelections: {} })}>
          Clear all
        </button>
      </div>

      <div className="calgetc-areas">
        {visibleAreas.map(area => (
          <AreaCard
            key={area.id}
            area={area}
            selected={selections[area.id] || []}
            autoSelected={autoSelections[area.id] || []}
            inPlan={inPlan}
            onToggle={handleToggle}
            expanded={expandedId === area.id}
            onToggleExpand={id => setExpandedId(prev => prev === id ? null : id)}
          />
        ))}
      </div>

      {completedCount === totalAreas && (
        <div className="calgetc-complete-banner">
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="8" fill="var(--green-bg)"/><path d="M6 10l2.5 2.5L14 7" stroke="var(--green)" strokeWidth="2" strokeLinecap="round"/></svg>
          <span>All {totalAreas} areas complete! Your Cal-GETC is certified.</span>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CalGETCView });
