/* =========================================================================
 *  CTWCAD — Page views (dashboard, browser, settings, trash, sign-in, marketing)
 * =======================================================================*/

/* ---------- DASHBOARD ----------------------------------------------- */
function DashboardView({ user, onOpenFile, onOpenProject, onUpload, onNewProject }) {
  const [pinned, setPinned] = useState(null);
  const [recent, setRecent] = useState(null);
  const [activity, setActivity] = useState(null);
  const [contextMenu, setContextMenu] = useState(null);

  useEffect(() => {
    window.api.listPinnedProjects().then(setPinned);
    window.api.listRecentFiles(8).then(setRecent);
    window.api.listActivity().then(setActivity);
  }, []);

  const firstName = (user?.name || user?.email || "").split(/[\s@]/)[0] || "there";
  const subline = recent && recent.length > 0
    ? `${recent.length} recent file${recent.length === 1 ? "" : "s"} · last updated ${fmtRelative(recent[0].updatedAt)}`
    : "Drop a file here or click Upload to get started.";

  // Re-fetch when files/projects change anywhere in the app.
  useEffect(() => {
    const refresh = () => {
      window.api.listPinnedProjects().then(setPinned);
      window.api.listRecentFiles(8).then(setRecent);
      window.api.listActivity().then(setActivity);
    };
    window.addEventListener("ctwcad:folder-changed", refresh);
    window.addEventListener("ctwcad:project-created", refresh);
    return () => {
      window.removeEventListener("ctwcad:folder-changed", refresh);
      window.removeEventListener("ctwcad:project-created", refresh);
    };
  }, []);

  const onProjectContext = (e, project) => {
    e.preventDefault();
    setContextMenu({
      kind: "project",
      project,
      x: Math.min(e.clientX, window.innerWidth - 240),
      y: Math.min(e.clientY, window.innerHeight - 360),
      ox: 0, oy: 0,
    });
  };
  const onFileContext = (e, file) => {
    e.preventDefault();
    setContextMenu({
      kind: "file",
      file,
      x: Math.min(e.clientX, window.innerWidth - 240),
      y: Math.min(e.clientY, window.innerHeight - 320),
      ox: 0, oy: 0,
    });
  };

  const M = window.FramerMotion.motion;
  return (
    <div className="ct-page">
      <div className="ct-page-head">
        <div>
          <div className="ct-eyebrow ct-mono">DASHBOARD</div>
          <h1>Welcome back, {firstName}.</h1>
          <p className="ct-dim">{subline}</p>
        </div>
        <div className="ct-page-head-cta" data-tour="upload-cta">
          <button className="ct-btn ct-btn-ghost" onClick={onUpload}><Icon name="upload-cloud" size={14}/>Upload</button>
          <button className="ct-btn ct-btn-primary" onClick={onNewProject}><Icon name="plus" size={14}/>New project</button>
        </div>
      </div>

      <section className="ct-section">
        <h2>Pinned projects</h2>
        {pinned && pinned.length === 0 ? (
          <div className="ct-empty ct-empty-soft">
            <Icon name="pin" size={24}/>
            <div className="ct-empty-title">No pinned projects yet</div>
            <div className="ct-dim" style={{maxWidth: 380, textAlign: "center"}}>
              Right-click any project and choose <span className="ct-mono">Pin to dashboard</span> to keep it here.
            </div>
            <button className="ct-btn ct-btn-ghost" onClick={onNewProject} style={{marginTop:6}}>
              <Icon name="plus" size={13}/>New project
            </button>
          </div>
        ) : (
          <div className="ct-projects-grid">
            {(pinned || Array.from({length: 3})).map((p, i) => (
              p ? <ProjectCard key={p.id} project={p} index={i}
                                onOpen={() => onOpenProject(p)}
                                onContextMenu={(e) => onProjectContext(e, p)} />
                : <div key={i} className="ct-project-card ct-skeleton" />
            ))}
          </div>
        )}
      </section>

      <div className="ct-row-split">
        <section className="ct-section">
          <h2>Recent files</h2>
          {recent && recent.length === 0 ? (
            <div className="ct-empty ct-empty-soft">
              <Icon name="file-plus" size={24}/>
              <div className="ct-empty-title">No files yet</div>
              <div className="ct-dim" style={{maxWidth: 360, textAlign: "center"}}>
                Drop files anywhere on this page or click <span className="ct-mono">Upload</span> to put your first part in the cloud.
              </div>
              <button className="ct-btn ct-btn-primary" onClick={onUpload} style={{marginTop:6}}>
                <Icon name="upload-cloud" size={13}/>Upload files
              </button>
            </div>
          ) : (
            <div className="ct-recent-list">
              {(recent || Array.from({length: 6})).map((f, i) => (
                f ? (
                  <M.div key={f.id} className="ct-recent-row"
                    initial={{ opacity: 0, x: -8 }} animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: i * 0.04, duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
                    onClick={() => onOpenFile(f.id)}
                    onContextMenu={(e) => onFileContext(e, f)}>
                    <div className="ct-recent-thumb"><CADThumb file={f} /></div>
                    <div className="ct-recent-meta">
                      <div className="ct-recent-name">{f.name}</div>
                      <div className="ct-mono ct-dim">v{f.versionCount} · {fmtBytes(f.sizeBytes)} · {fmtRelative(f.updatedAt)}</div>
                    </div>
                    <Icon name="chevron-right" size={14}/>
                  </M.div>
                ) : <div key={i} className="ct-recent-row ct-skeleton" style={{ height: 60 }} />
              ))}
            </div>
          )}
        </section>

        <section className="ct-section">
          <h2>Activity</h2>
          <ActivityFeed events={activity} onOpenFile={onOpenFile}
            onFileContext={onFileContext} />
        </section>
      </div>

      <ContextMenu menu={contextMenu} onClose={() => setContextMenu(null)} />
    </div>
  );
}

function ProjectCard({ project, onOpen, onContextMenu, index = 0 }) {
  const M = window.FramerMotion.motion;
  return (
    <M.div
      className="ct-project-card"
      onClick={onOpen}
      onContextMenu={onContextMenu}
      layoutId={`project-${project.id}`}
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: index * 0.05, type: "spring", stiffness: 240, damping: 24 }}
      whileHover={{ y: -4 }}
    >
      <div className="ct-project-cover" style={{
        background: `linear-gradient(135deg,
          oklch(0.42 0.10 ${project.coverHue}) 0%,
          oklch(0.22 0.06 ${project.coverHue + 30}) 100%)`,
      }}>
        <svg viewBox="0 0 200 120" className="ct-project-iso">
          <g stroke="rgba(255,255,255,0.7)" strokeWidth="0.6" fill="none">
            {Array.from({length: 8}).map((_, i) => (
              <path key={i} d={`M${20 + i * 22} 100 L${50 + i * 22} 70 L${80 + i * 22} 100 L${50 + i * 22} 130 z`} opacity={1 - i * 0.08}/>
            ))}
          </g>
        </svg>
        <span className="ct-project-pin"><Icon name="pin" size={12}/></span>
      </div>
      <div className="ct-project-meta">
        <div className="ct-project-name">{project.name}</div>
        <div className="ct-project-sub ct-dim">{project.description}</div>
        <div className="ct-project-foot">
          <span className="ct-mono ct-dim">{project.memberCount} members</span>
          <span className="ct-dot"/>
          <span className="ct-mono ct-dim">{fmtRelative(project.updatedAt)}</span>
        </div>
      </div>
    </M.div>
  );
}

function ActivityFeed({ events, onOpenFile, onFileContext }) {
  const M = window.FramerMotion.motion;
  if (!events) return <div className="ct-skeleton" style={{height: 220}}/>;
  // Friendly empty-state replaces a blank panel for fresh accounts. Once
  // the user uploads or syncs, the activity log fills in via the
  // ctwcad:folder-changed listener that re-fetches everything on the
  // dashboard.
  if (events.length === 0) {
    return (
      <div className="ct-empty ct-empty-soft">
        <Icon name="activity" size={24}/>
        <div className="ct-empty-title">No activity yet</div>
        <div className="ct-dim" style={{maxWidth: 320, textAlign: "center"}}>
          Saves, uploads, and renames will show up here.
        </div>
      </div>
    );
  }
  return (
    <ul className="ct-activity">
      {events.map((ev, i) => (
        <M.li key={ev.id} className="ct-activity-item"
          initial={{ opacity: 0, x: -8 }} animate={{ opacity: 1, x: 0 }}
          transition={{ delay: i * 0.05, duration: 0.3 }}
          onClick={() => ev.file && onOpenFile(ev.file.id)}
          onContextMenu={(e) => ev.file && onFileContext?.(e, ev.file)}>
          <span className={"ct-activity-dot " + (ev.source === "ctwcad" ? "is-cad" : "is-web")}/>
          <div className="ct-activity-body">
            <div>
              <strong>{labelForEvent(ev)}</strong>
              {ev.file && <span className="ct-mono"> {ev.file.name}</span>}
            </div>
            <div className="ct-dim ct-mono">
              {ev.source === "ctwcad" ? `CTWCAD · ${ev.deviceName}` : "Web"}
              <span className="ct-dot"/>
              {fmtRelative(ev.at)}
            </div>
          </div>
        </M.li>
      ))}
    </ul>
  );
}
function labelForEvent(ev) {
  switch (ev.type) {
    case "version.created": return "Saved new version of";
    case "file.created":    return "Uploaded";
    case "file.renamed":    return "Renamed";
    case "file.moved":      return "Moved";
    case "file.trashed":    return "Trashed";
    default: return ev.type;
  }
}

Object.assign(window, { DashboardView, ProjectCard, ActivityFeed });
