/* Rank Lyx - Home
   Visual Home overview rendered through the existing dashboard route. */

const HOME_METRIC_COLORS = {
  Guide: '#2563EB',
  Roundup: '#F97316',
  Comparison: '#10B981',
  'Single Review': '#8B5CF6',
  Other: '#6B7280'
};

const HOME_METRIC_FALLBACK = {
  totalWords: 0,
  totalWordsDisplay: '0',
  totalHours: 0,
  totalHoursDisplay: '0h',
  breakdown: []
};

function getHomeMetricColor(label, index) {
  const fallback = ['#2563EB', '#F97316', '#6B7280', '#10B981', '#8B5CF6'];
  return HOME_METRIC_COLORS[label] || fallback[index % fallback.length];
}

function buildHomeBreakdownItems(items, valueKey, amountKey) {
  return (Array.isArray(items) ? items : []).map((item, index) => ({
    label: item.label,
    value: item[valueKey],
    amount: item[amountKey],
    color: getHomeMetricColor(item.label, index)
  }));
}

function MetricDonutBreakdownCard({ title, items, emptyLabel }) {
  const circumference = 100;
  const gap = 7;
  const total = items.reduce((sum, item) => sum + item.amount, 0) || 1;
  const drawable = circumference - gap * items.length;
  let offset = 0;

  return (
    <div className="rl-home-card rl-home-card--breakdown">
      <span className="rl-home-card__label">{title}</span>
      {items.length ?
      <div className="rl-home-breakdown">
        <svg className="rl-home-donut" viewBox="0 0 44 44" aria-hidden="true" focusable="false">
          <circle className="rl-home-donut__track" cx="22" cy="22" r="15.915" />
          {items.map((item) => {
            const segment = item.amount / total * drawable;
            const dashOffset = -offset;
            offset += segment + gap;
            return (
              <circle
                key={item.label}
                className="rl-home-donut__segment"
                cx="22"
                cy="22"
                r="15.915"
                style={{ stroke: item.color, strokeDasharray: `${segment} ${circumference - segment}`, strokeDashoffset: dashOffset }} />);
          })}
        </svg>
        <div className="rl-home-breakdown__legend">
          {items.map((item) =>
          <div className="rl-home-breakdown__row" key={item.label}>
              <span className="rl-home-breakdown__name">
                <span className="rl-home-breakdown__mark" style={{ background: item.color }}></span>
                <span className="rl-home-breakdown__label">{item.label}</span>
              </span>
              <span className="rl-home-breakdown__value">{item.value}</span>
            </div>
          )}
        </div>
      </div> :
      <div className="rl-home-breakdown rl-home-breakdown--empty">
        <span className="rl-home-breakdown__empty">{emptyLabel}</span>
      </div>
      }
    </div>);
}

function MetricBarBreakdownCard({ title, items, emptyLabel }) {
  const total = items.reduce((sum, item) => sum + item.amount, 0) || 1;

  return (
    <div className="rl-home-card rl-home-card--breakdown rl-home-card--bar">
      <span className="rl-home-card__label">{title}</span>
      {items.length ?
      <div className="rl-home-bar-stack">
        <div className="rl-home-bar" aria-hidden="true">
          {items.map((item) =>
          <span
            key={item.label}
            className="rl-home-bar__segment"
            style={{ background: item.color, flexBasis: `${item.amount / total * 100}%` }}>
          </span>
          )}
        </div>
        <div className="rl-home-breakdown__legend">
          {items.map((item) =>
          <div className="rl-home-breakdown__row" key={item.label}>
              <span className="rl-home-breakdown__name">
                <span className="rl-home-breakdown__mark" style={{ background: item.color }}></span>
                <span className="rl-home-breakdown__label">{item.label}</span>
              </span>
              <span className="rl-home-breakdown__value">: {item.value}</span>
            </div>
          )}
        </div>
      </div> :
      <div className="rl-home-bar-stack rl-home-breakdown--empty">
        <span className="rl-home-breakdown__empty">{emptyLabel}</span>
      </div>
      }
    </div>);
}

function Dashboard({ onNavigate, onOpenArticle, articleCollection, workspaceAccess, websites }) {
  React.useEffect(() => {if (window.lucide) window.lucide.createIcons();});

  const canStartArticle = workspaceAccess && workspaceAccess.canStartArticleWorkflow === true;
  const accessDescriptionId = !canStartArticle && workspaceAccess && workspaceAccess.noticeMessage ? 'rl-workspace-access-notice' : undefined;
  const go = (id) => {if (onNavigate) onNavigate(id);};

  const currentUser = typeof getCurrentAccountUser === 'function' ? getCurrentAccountUser() : null;
  const library = typeof window !== 'undefined' ? window.RankLyxCloudArticleLibrary : null;
  const collectionStatus = articleCollection && articleCollection.status || 'loading';
  const loadedRecords = collectionStatus === 'ready' && Array.isArray(articleCollection.articles) ? articleCollection.articles : [];
  const metricRecords = library && typeof library.filterCloudArticles === 'function' ?
    library.filterCloudArticles(loadedRecords) : [];
  const readyMetrics = collectionStatus === 'ready' && typeof window !== 'undefined' && window.ContentMetrics &&
    typeof window.ContentMetrics.buildContentMetrics === 'function' && currentUser && currentUser.id ?
  window.ContentMetrics.buildContentMetrics(metricRecords, currentUser.id, {
    countWords: typeof countArticleWords === 'function' ? countArticleWords : undefined,
    normalizePostType: typeof normalizeArticlePostType === 'function' ? normalizeArticlePostType : undefined
  }) :
  HOME_METRIC_FALLBACK;
  const contentMetrics = collectionStatus === 'ready' ? readyMetrics : {
    ...HOME_METRIC_FALLBACK,
    totalWordsDisplay: collectionStatus === 'error' ? 'Unavailable' : 'Loading...',
    totalHoursDisplay: collectionStatus === 'error' ? 'Unavailable' : 'Loading...'
  };
  const metricEmptyLabel = collectionStatus === 'error' ? 'Article data unavailable' :
    collectionStatus === 'loading' ? 'Loading article data...' : 'No drafted words yet';
  const timeEmptyLabel = collectionStatus === 'error' ? 'Article data unavailable' :
    collectionStatus === 'loading' ? 'Loading article data...' : 'No drafted time yet';
  const wordsByPostType = buildHomeBreakdownItems(contentMetrics.breakdown, 'wordsDisplay', 'words');
  const timeByPostType = buildHomeBreakdownItems(contentMetrics.breakdown, 'hoursDisplay', 'hours');
  const articleRows = collectionStatus === 'ready' && currentUser && currentUser.id &&
    library && typeof library.buildOwnedRecentRows === 'function' ?
    library.buildOwnedRecentRows(metricRecords, currentUser.id, {
      limit: 10,
      countWords: typeof countArticleWords === 'function' ? countArticleWords : undefined,
      getInitials: typeof getInitials === 'function' ? getInitials : undefined
    }) :
  [];

  const DAY = 864e5;
  const fmtDue = (ms) =>
  new Date(ms).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });

  const calendarSource = [
  { title: 'Spring launch recap', publishAt: Date.now() - 1 * DAY },
  { title: 'Churn email guide', publishAt: Date.now() + 1 * DAY },
  { title: 'Newsletter - June', publishAt: Date.now() + 4 * DAY },
  { title: 'Product update post', publishAt: Date.now() + 8 * DAY },
  { title: 'Quarterly SEO report', publishAt: Date.now() + 12 * DAY }];

  const upcoming = calendarSource.
  filter((item) => item.publishAt > Date.now()).
  sort((a, b) => a.publishAt - b.publishAt).
  slice(0, 4);

  const knowledgeLinks = [
  { label: 'Brand Profile', route: 'brand-profile' },
  { label: 'Product Knowledge', route: 'product-knowledge' },
  { label: 'Audience & ICP', route: 'audience-icp' },
  { label: 'Brand Voice', route: 'brand-voice' }];

  return (
    <main className="rl-page rl-dash" data-screen-label="Home">
      <div className="rl-dash__inner">
        <header className="rl-home-head">
          <h1>Home</h1>
          <p>Track your writing workspace and jump back into the next useful action.</p>
        </header>

        <section className="rl-home-top" aria-label="Home summary">
          <button type="button" className="rl-home-card rl-home-card--action rl-home-card--write" onClick={() => canStartArticle && go('ai-writer')} disabled={!canStartArticle} aria-describedby={accessDescriptionId}>
            <span className="rl-home-write__art" aria-hidden="true">
              <span className="rl-home-write__paper">
                <span></span>
                <span></span>
                <span></span>
              </span>
              <span className="rl-home-write__spark rl-home-write__spark--one"></span>
              <span className="rl-home-write__spark rl-home-write__spark--two"></span>
            </span>
            <span className="rl-home-write__top">
              <span className="rl-home-card__icon rl-home-write__icon"><i data-lucide="pen-line"></i></span>
              <span className="rl-home-write__copy">
                <span className="rl-home-card__title">Write article</span>
                <span className="rl-home-write__sub">Create a new draft</span>
              </span>
            </span>
            <span className="rl-home-write__cta">
              <span><i data-lucide="plus"></i>Start from a brief</span>
              <i data-lucide="arrow-right"></i>
            </span>
          </button>

          <div className="rl-home-card rl-home-card--metric rl-home-card--metric-words">
            <div className="rl-home-card__metric-row">
              <span className="rl-home-card__label">Words generated</span>
              <span className="rl-home-card__metric">{contentMetrics.totalWordsDisplay}</span>
            </div>
            <svg className="rl-home-spark" viewBox="0 0 240 82" preserveAspectRatio="none" aria-hidden="true" focusable="false">
              <defs>
                <linearGradient id="rl-home-words-fill" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#22C55E" stopOpacity="0.2" />
                  <stop offset="100%" stopColor="#22C55E" stopOpacity="0" />
                </linearGradient>
              </defs>
              <path className="rl-home-spark__fill" d="M4 69 C30 58 48 57 71 45 C98 31 113 11 143 24 C168 35 181 21 205 22 C221 23 229 18 236 10 L236 82 L4 82 Z" fill="url(#rl-home-words-fill)" />
              <path className="rl-home-spark__line" d="M4 69 C30 58 48 57 71 45 C98 31 113 11 143 24 C168 35 181 21 205 22 C221 23 229 18 236 10" />
            </svg>
          </div>

          <MetricDonutBreakdownCard title="Words by post type" items={wordsByPostType} emptyLabel={metricEmptyLabel} />

          <div className="rl-home-card rl-home-card--metric rl-home-card--metric-time">
            <div className="rl-home-card__metric-row">
              <span className="rl-home-card__label">Time saved</span>
              <span className="rl-home-card__metric">{contentMetrics.totalHoursDisplay}</span>
            </div>
            <svg className="rl-home-spark" viewBox="0 0 240 82" preserveAspectRatio="none" aria-hidden="true" focusable="false">
              <defs>
                <linearGradient id="rl-home-time-fill" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#F97316" stopOpacity="0.2" />
                  <stop offset="100%" stopColor="#F97316" stopOpacity="0" />
                </linearGradient>
              </defs>
              <path className="rl-home-spark__fill" d="M4 72 C27 48 47 57 67 42 C89 26 105 29 124 36 C146 44 157 20 181 25 C203 29 216 33 236 17 L236 82 L4 82 Z" fill="url(#rl-home-time-fill)" />
              <path className="rl-home-spark__line" d="M4 72 C27 48 47 57 67 42 C89 26 105 29 124 36 C146 44 157 20 181 25 C203 29 216 33 236 17" />
            </svg>
          </div>

          <MetricBarBreakdownCard title="Time by post type" items={timeByPostType} emptyLabel={timeEmptyLabel} />
        </section>

        <section className="rl-home-section rl-home-section--articles">
          {collectionStatus === 'loading' ?
          <section className="rl-articles__empty rl-home-empty" role="status">
              <span className="rl-articles__empty-icon"><i data-lucide="loader-circle"></i></span>
              <h2>Loading recent articles</h2>
              <p>Fetching your latest saved Workspace articles.</p>
            </section> :
          collectionStatus === 'error' ?
          <section className="rl-articles__empty rl-home-empty" role="alert">
              <span className="rl-articles__empty-icon"><i data-lucide="cloud-off"></i></span>
              <h2>Recent articles are unavailable</h2>
              <p>{articleCollection && articleCollection.error || 'Article data could not be loaded right now.'}</p>
              <button type="button" className="rl-btn rl-btn--primary" onClick={() => articleCollection && articleCollection.retry && articleCollection.retry()}>
                <i data-lucide="refresh-cw"></i><span>Try again</span>
              </button>
            </section> :
          articleRows.length && typeof ArticleLibraryTable === 'function' ?
          <ArticleLibraryTable rows={articleRows} onOpenArticle={onOpenArticle} /> :
          <section className="rl-articles__empty rl-home-empty">
              <span className="rl-articles__empty-icon"><i data-lucide="file-text"></i></span>
              <h2>No articles yet</h2>
              <p>Your latest articles will appear here after you create them.</p>
            </section>
          }
        </section>

        <section className="rl-home-bottom" aria-label="Workspace shortcuts">
          <section className="rl-home-panel">
            <div className="rl-home-panel__head">
              <h2>Upcoming Content</h2>
            </div>
            <div className="rl-home-list">
              {upcoming.map((item) =>
              <div className="rl-home-list__row" key={item.title}>
                  <strong>{item.title}</strong>
                  <span>Due {fmtDue(item.publishAt)}</span>
                </div>
              )}
            </div>
          </section>

          {websites ? <window.ClicklyxWebsitesUI.HomeWebsites state={websites} onNavigate={onNavigate} /> : (          <section className="rl-home-panel">
            <div className="rl-home-panel__head">
              <h2>Knowledge</h2>
            </div>
            <div className="rl-home-knowledge">
              {knowledgeLinks.map((item) =>
              <button type="button" key={item.route} onClick={() => go(item.route)}>
                  <span>{item.label}</span>
                  <i data-lucide="arrow-right"></i>
                </button>
              )}
            </div>
          </section>)}


          <section className="rl-home-panel">
            <div className="rl-home-panel__head">
              <h2>Recent AI Chats</h2>
            </div>
            <div className="rl-home-soon">
              <div className="rl-home-chat-preview" aria-hidden="true">
                <span className="rl-home-chat-preview__bubble rl-home-chat-preview__bubble--one"></span>
                <span className="rl-home-chat-preview__bubble rl-home-chat-preview__bubble--two"></span>
                <span className="rl-home-chat-preview__bubble rl-home-chat-preview__bubble--three"></span>
              </div>
              <div className="rl-home-chat-soon">
                <span className="rl-home-chat-soon__left">
                  <span className="rl-home-chat-soon__icon"><i data-lucide="sparkles"></i></span>
                  <span className="rl-home-chat-soon__badge">Coming soon</span>
                </span>
                <strong>AI Chat is coming soon</strong>
              </div>
            </div>
          </section>
        </section>
      </div>
    </main>);
}
