// SlothApp - Google Docs / Sheets / Slides / Forms activity collector.
//
// Captures: doc id, kind, title, edit-vs-view flag. The base activity
// tracker already counts time-on-tab, so this content script only enriches
// it with document metadata that the URL alone can't reveal.
//
// URL patterns:
//   docs.google.com/document/d/{ID}/edit       — Docs
//   docs.google.com/spreadsheets/d/{ID}/edit   — Sheets
//   docs.google.com/presentation/d/{ID}/edit   — Slides
//   docs.google.com/forms/d/{ID}/edit          — Forms

(() => {
    const REPORT_INTERVAL_MS = 15000;   // re-report every 15s while active
    const EDIT_FLUSH_MS = 4000;         // 4s after a keystroke, flush as 'edited'

    function detectKind(href) {
        if (/\/spreadsheets\/d\//.test(href)) return 'sheet';
        if (/\/presentation\/d\//.test(href)) return 'slide';
        if (/\/forms\/d\//.test(href))        return 'form';
        if (/\/document\/d\//.test(href))     return 'doc';
        return null;
    }

    function extractDocId(href) {
        const m = href.match(/\/(?:document|spreadsheets|presentation|forms)\/d\/([a-zA-Z0-9_\-]+)/);
        return m ? m[1] : null;
    }

    function extractTitle() {
        // The reliable title sources, in priority order:
        //   1) <title> tag — "DocTitle - Google Docs"
        //   2) input[aria-label="문서 이름"] / "Document title" — Docs renames field
        //   3) #docs-title-input — legacy Docs
        //   4) document.title minus the trailing "- Google {Kind}"
        const inputSelectors = [
            'input[aria-label="문서 이름"]',
            'input[aria-label="Document title"]',
            'input[aria-label="Rename"]',
            '#docs-title-input',
            '#docs-title-input-label-inner',
        ];
        for (const sel of inputSelectors) {
            const el = document.querySelector(sel);
            const v = el ? (el.value || el.innerText || '').trim() : '';
            if (v && v.length > 0) return v;
        }
        const raw = (document.title || '').trim();
        const cleaned = raw
            .replace(/\s*-\s*Google\s+(Docs|Sheets|Slides|Forms|문서|스프레드시트|프레젠테이션|설문지)\s*$/i, '')
            .replace(/\s*[-–]\s*Google\s+Workspace.*$/i, '')
            .trim();
        return cleaned || raw || '(제목 없음)';
    }

    let cleanedUp = false;
    let urlPollInterval = null;
    let reportInterval = null;
    let editFlushTimer = null;
    let openedAt = new Date();
    let lastActiveAt = new Date();
    let didEditThisSession = false;
    let lastUrl = location.href;

    function isExtAlive() {
        try { return !!(chrome && chrome.runtime && chrome.runtime.id); }
        catch (_) { return false; }
    }

    function cleanup() {
        if (cleanedUp) return;
        cleanedUp = true;
        if (reportInterval) clearInterval(reportInterval);
        if (urlPollInterval) clearInterval(urlPollInterval);
        if (editFlushTimer) clearTimeout(editFlushTimer);
        document.removeEventListener('keydown', onUserEdit, true);
        document.removeEventListener('input',   onUserEdit, true);
        console.log('[SlothApp] Google Docs collector stopped.');
    }

    function safeSend(payload) {
        if (cleanedUp) return;
        if (!isExtAlive()) { cleanup(); return; }
        try {
            chrome.runtime.sendMessage(payload, () => {
                try { void chrome.runtime.lastError; } catch (_) {}
            });
        } catch (_) { cleanup(); }
    }

    function reportNow() {
        const href = location.href;
        const kind = detectKind(href);
        const docId = extractDocId(href);
        if (!kind || !docId) return;   // not on a doc — bail
        const title = extractTitle();
        lastActiveAt = new Date();
        safeSend({
            type: 'gwsDocActivity',
            gwsDoc: {
                docId,
                kind,
                title,
                didEdit: didEditThisSession,
                url: href,
                openedAt: openedAt.toISOString(),
                lastActiveAt: lastActiveAt.toISOString(),
            },
        });
    }

    function onUrlChanged() {
        const href = location.href;
        if (href === lastUrl) return;
        // Reset session state when navigating to a different doc.
        const oldId = extractDocId(lastUrl);
        const newId = extractDocId(href);
        lastUrl = href;
        if (oldId !== newId) {
            openedAt = new Date();
            didEditThisSession = false;
        }
        // Wait a tick for the new title to render, then report.
        setTimeout(reportNow, 1500);
    }

    function onUserEdit(e) {
        // Filter out keystrokes inside the title rename field — those aren't
        // really 'edits' to the body. But still useful as a signal of activity.
        if (didEditThisSession) {
            lastActiveAt = new Date();
            return;
        }
        didEditThisSession = true;
        lastActiveAt = new Date();
        if (editFlushTimer) clearTimeout(editFlushTimer);
        // Brief debounce so we don't flood on the first keystroke storm.
        editFlushTimer = setTimeout(reportNow, EDIT_FLUSH_MS);
    }

    // ---- Wire-up ----

    // First report once the page is ready enough to have a title.
    setTimeout(reportNow, 2500);

    // Periodic refresh so the lastActiveAt timestamp stays current.
    reportInterval = setInterval(() => {
        if (cleanedUp) return;
        if (!isExtAlive()) { cleanup(); return; }
        // Only emit if the tab is currently visible — otherwise we'd inflate
        // 'active' time for a tab the user left in the background.
        if (document.visibilityState !== 'visible') return;
        reportNow();
    }, REPORT_INTERVAL_MS);

    // Detect SPA navigation (especially in Slides where the URL changes by
    // slide number, and across Docs/Sheets if user opens via the open dialog).
    urlPollInterval = setInterval(() => {
        if (cleanedUp) return;
        if (!isExtAlive()) { cleanup(); return; }
        onUrlChanged();
    }, 1500);

    // Edit detection: any keystroke or input event on the page counts.
    document.addEventListener('keydown', onUserEdit, true);
    document.addEventListener('input',   onUserEdit, true);

    window.addEventListener('pagehide', () => {
        // Final flush so we capture didEdit before the tab unloads.
        try { reportNow(); } catch (_) {}
        cleanup();
    }, { once: true });

    console.log('[SlothApp] Google Docs collector active.');
})();
