/* global React */
const { useState, useEffect } = React;

const WP_EVIDENCE_LABELS = {
  segment: 'Segments',
  repeated_behavior: 'Repeated behavior',
  action: 'Actions',
  tension: 'Tensions',
};

const wpText = (value) => String(value || '').replace(/\s+/g, ' ').trim();

const wpHumanize = (value) =>
  wpText(value).replace(/[_-]+/g, ' ').split(' ').map((w) => (w ? w.charAt(0).toUpperCase() + w.slice(1) : w)).join(' ');

const wpQuote = (value, max = 118) => {
  const text = wpText(value);
  if (!text) return '';
  if (text.length <= max) return text;
  return text.slice(0, max).replace(/\s+\S*$/, '') + '...';
};

const formatStaleLabel = (hours) => {
  const value = Number(hours || 0);
  if (value <= 6) return 'Fresh today';
  if (value < 48) return `${Math.round(value)}h old`;
  const days = Math.round(value / 24);
  if (days < 14) return `${days}d old`;
  return `${Math.round(days / 7)}w old`;
};

const evidenceCountLabel = (summary = {}) => {
  const segments = Number(summary.segment_count || 0);
  const repeated = Number(summary.repeated_behavior_count || 0);
  const actions = Number(summary.action_count || 0);
  const parts = [];
  if (segments) parts.push(`${segments} segment${segments === 1 ? '' : 's'}`);
  if (repeated) parts.push(`${repeated} repeated`);
  if (actions) parts.push(`${actions} action${actions === 1 ? '' : 's'}`);
  return parts.length ? parts.join(' / ') : 'Evidence pending';
};

const groupWaypointEvidence = (wp) => {
  const grouped = {
    repeated_behavior: [],
    action: [],
    segment: [],
    tension: [],
  };
  (wp.evidence || []).forEach((item, index) => {
    const type = grouped[item.type] ? item.type : 'segment';
    const isBehavior = (type === 'repeated_behavior' || type === 'tension');
    const rawText = wpText(item.label) || wpText(item.excerpt || item.detail || item.text);
    grouped[type].push({
      id: item.id || `${wp.id}-evidence-${index}`,
      label: isBehavior
        ? (wpHumanize(rawText) || WP_EVIDENCE_LABELS[type] || 'Evidence')
        : (wpText(item.label) || WP_EVIDENCE_LABELS[type] || 'Evidence'),
      excerpt: isBehavior ? '' : wpQuote(item.excerpt || item.detail || item.text, type === 'segment' ? 150 : 110),
      date: item.date || '',
      sourceId: item.sourceId || '',
    });
  });
  return grouped;
};

const PlottingCard = ({ domainKey }) => {
  const label = (domainKey || 'domain').replace('_', ' ');
  return (
    <article className="wp wp--plotting" aria-hidden="true">
      <div className="wp__plotting-pulse">
        <span className="wp__plotting-center" />
      </div>
      <p className="wp__plotting-label">
        Plotting coordinates...<br />
        <em style={{ textTransform: 'none', letterSpacing: 0 }}>{label}</em>
      </p>
    </article>
  );
};

const WaypointCard = ({ wp, onOpen }) => {
  const summary = wp.evidenceSummary || {};
  return (
    <article
      className={'wp wp--clickable' + (wp.staleHours > 36 ? ' wp--aged' : '')}
      style={{ '--domain-color': wp.color }}
      role="button"
      tabIndex={0}
      aria-label={`Open waypoint for ${wp.valueGoal}`}
      onClick={() => onOpen(wp)}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          onOpen(wp);
        }
      }}
    >
      <span className="wp__value-label">{wp.valueGoal}</span>
      <blockquote className="wp__quote">{wp.headline}</blockquote>
      <p className="wp__description">{wp.description}</p>
      <div className="dash2-mirror-card__evidence">
        <span>{wp.domain}</span>
        <span>{evidenceCountLabel(summary)}</span>
        <span>{formatStaleLabel(wp.staleHours)}</span>
      </div>
      <div className="wp__actions">
        <span className="wp__hint">View evidence</span>
        <button
          className="btn-execute wp__cta"
          type="button"
          onClick={(e) => { e.stopPropagation(); onOpen(wp); }}
        >
          Reflect
        </button>
      </div>
    </article>
  );
};

const WaypointEvidenceList = ({ title, items, emptyText }) => (
  <section className="wp-drawer__section">
    <div className="wp-drawer__section-head">
      <span className="label-caps">{title}</span>
      <span className="wp-drawer__count">{items.length}</span>
    </div>
    {items.length > 0 ? (
      <div className="wp-drawer__items">
        {items.map(item => (
          <article key={item.id} className="wp-drawer__item">
            <div className="wp-drawer__item-top">
              <strong className="wp-drawer__item-label">{item.label}</strong>
              {item.date ? <span className="wp-drawer__item-meta">{item.date}</span> : null}
            </div>
            {item.excerpt ? <p className="wp-drawer__item-detail">{item.excerpt}</p> : null}
          </article>
        ))}
      </div>
    ) : (
      <p className="wp-drawer__empty">{emptyText}</p>
    )}
  </section>
);

const WaypointDrawer = ({ waypoint, onClose }) => {
  const [reflection, setReflection] = useState('');
  const [showOptional, setShowOptional] = useState(false);

  useEffect(() => {
    if (!waypoint) return;
    setReflection('');
    setShowOptional(false);
  }, [waypoint && waypoint.id]);

  useEffect(() => {
    if (!waypoint) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prevOverflow; };
  }, [waypoint]);

  useEffect(() => {
    if (!waypoint) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [waypoint, onClose]);

  if (!waypoint) return null;

  const evidence = groupWaypointEvidence(waypoint);
  const summary = waypoint.evidenceSummary || {};

  return (
    <div className="wp-modal wp-modal--drawer" onClick={onClose}>
      <aside
        className="wp-modal__panel wp-modal__panel--drawer"
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-label={`${waypoint.valueGoal} evidence drawer`}
      >
        <button className="wp-drawer__close" onClick={onClose} aria-label="Close drawer">x</button>

        <header className="wp-drawer__head">
          <p className="label-caps wp-drawer__kicker">Reflection coordinate</p>
          <h3 className="wp-drawer__title">{waypoint.headline}</h3>
          <p className="wp-drawer__value">{waypoint.valueGoal}</p>
          <p className="wp-drawer__description">{waypoint.description}</p>
          <div className="wp-drawer__meta">
            <span>{waypoint.domain}</span>
            <span>{evidenceCountLabel(summary)}</span>
            <span>{summary.date_range_label || formatStaleLabel(waypoint.staleHours)}</span>
          </div>
        </header>

        <div className="wp-drawer__body">
          <section className="wp-drawer__section">
            <label className="label-caps" htmlFor="waypoint-reflection">What made this possible?</label>
            <textarea
              id="waypoint-reflection"
              className="wp-drawer__textarea"
              rows="4"
              value={reflection}
              onChange={(e) => setReflection(e.target.value)}
              placeholder="Name the pattern, support, or condition you want to remember."
            />
            <div className="wp-drawer__actions-row">
              <button className="wp-drawer__primary" type="button" onClick={onClose}>Save waypoint</button>
              <button className="wp-drawer__link" type="button">adjust meaning</button>
            </div>
          </section>

          <WaypointEvidenceList
            title="Repeated behavior"
            items={evidence.repeated_behavior}
            emptyText="No repeated behavior evidence is attached yet."
          />
          <WaypointEvidenceList
            title="Actions"
            items={evidence.action}
            emptyText="No action evidence is attached yet."
          />
          <WaypointEvidenceList
            title="Segments"
            items={evidence.segment}
            emptyText="No supporting segments were attached to this waypoint."
          />

          <details
            className="wp-drawer__optional"
            open={showOptional}
            onToggle={(e) => setShowOptional(e.currentTarget.open)}
          >
            <summary>Show optional notes</summary>
            <WaypointEvidenceList
              title="Tensions"
              items={evidence.tension}
              emptyText="No tension evidence is attached yet."
            />
          </details>
        </div>
      </aside>
    </div>
  );
};

const Waypoints = () => {
  const [waypoints, setWaypoints] = useState([]);
  const [plottingDomains, setPlottingDomains] = useState([]);
  const [active, setActive] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    fetch('/api/waypoints/today?limit=1')
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (!data) return;
        setWaypoints((data.waypoints || []).slice(0, 1));
        setPlottingDomains(data.plottingDomains || []);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const handleOpen = (wp) => setActive(wp);
  const handleClose = () => setActive(null);
  const plottingVisible = plottingDomains.slice(0, Math.max(0, 1 - waypoints.length));

  return (
    <section className="wp-section">
      <div className="section__head">
        <h2 className="section-title">Waypoint</h2>
        <span className="label-caps">reflection coordinate</span>
      </div>

      <div className="wp-grid">
        {waypoints.map(w => (
          <WaypointCard key={w.id} wp={w} onOpen={handleOpen} />
        ))}
        {plottingVisible.map(d => (
          <PlottingCard key={d} domainKey={d} />
        ))}
        {!loading && waypoints.length === 0 && plottingVisible.length === 0 && (
          <article className="wp wp--uncharted">
            <span className="wp__value-label">Uncharted</span>
            <p className="wp__description">No coordinates plotted yet.</p>
          </article>
        )}
      </div>

      <WaypointDrawer waypoint={active} onClose={handleClose} />
    </section>
  );
};

window.Waypoints = Waypoints;
